@runeditrun/rer 0.2.121 → 0.2.122

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 (146) hide show
  1. package/cli/README.md +124 -5
  2. package/cli/archive.mjs +1 -1
  3. package/cli/authoring.mjs +1 -1
  4. package/cli/browser-runtime.mjs +2 -2
  5. package/cli/business/agent-help.mjs +11 -11
  6. package/cli/business/agent-verbs.mjs +9 -8
  7. package/cli/business/api.mjs +11 -7
  8. package/cli/business/carry.mjs +4 -3
  9. package/cli/business/choices.mjs +1 -1
  10. package/cli/business/command.mjs +33 -11
  11. package/cli/business/connect.mjs +4 -4
  12. package/cli/business/credential-file.mjs +102 -0
  13. package/cli/business/errors.mjs +5 -2
  14. package/cli/business/invocation.mjs +7 -4
  15. package/cli/business/keychain.mjs +6 -2
  16. package/cli/business/local-commands.mjs +9 -3
  17. package/cli/business/mcp-bridge.mjs +2 -1
  18. package/cli/business/questions.mjs +1 -1
  19. package/cli/business/run-child.mjs +5 -5
  20. package/cli/business/run-grant.mjs +27 -8
  21. package/cli/business/run-mask.mjs +8 -1
  22. package/cli/business/scan-command.mjs +1 -1
  23. package/cli/business/service.mjs +4 -2
  24. package/cli/business/state.mjs +2 -2
  25. package/cli/checkout-folders.mjs +1 -1
  26. package/cli/checkout-preparation.mjs +4 -4
  27. package/cli/command-guidance.mjs +9 -0
  28. package/cli/companion/command.mjs +4 -3
  29. package/cli/companion/providers/sandbox.mjs +1 -1
  30. package/cli/companion/setup.mjs +4 -4
  31. package/cli/contract.mjs +8 -8
  32. package/cli/demo.mjs +1 -1
  33. package/cli/deploy-command.mjs +10 -5
  34. package/cli/deploy-hook.mjs +3 -2
  35. package/cli/deploy-inputs.mjs +7 -3
  36. package/cli/deploy-owner-input.mjs +2 -2
  37. package/cli/deploy-source.mjs +1 -1
  38. package/cli/deploy.mjs +4 -2
  39. package/cli/deployment-record.mjs +1 -1
  40. package/cli/dev-identity.mjs +4 -4
  41. package/cli/door-clauses.mjs +2 -2
  42. package/cli/door-mode.mjs +7 -7
  43. package/cli/door.mjs +7 -7
  44. package/cli/errors.mjs +15 -1
  45. package/cli/export-summary.mjs +1 -1
  46. package/cli/export.mjs +1 -1
  47. package/cli/hosted-export.mjs +1 -1
  48. package/cli/hosted-output.mjs +2 -2
  49. package/cli/human-error.mjs +8 -2
  50. package/cli/hydration/browser.mjs +1 -1
  51. package/cli/hydration/check.mjs +1 -1
  52. package/cli/import-summary.mjs +2 -2
  53. package/cli/inspect.mjs +3 -3
  54. package/cli/lifecycle.mjs +9 -9
  55. package/cli/listen.mjs +1 -1
  56. package/cli/listing.mjs +1 -1
  57. package/cli/local-env.mjs +1 -1
  58. package/cli/local.mjs +4 -4
  59. package/cli/managed-server.mjs +36 -13
  60. package/cli/output.mjs +2 -1
  61. package/cli/owner-entry-ready.mjs +92 -0
  62. package/cli/parse.mjs +8 -8
  63. package/cli/port.mjs +3 -3
  64. package/cli/portability-runtime.mjs +16 -0
  65. package/cli/portability.mjs +4 -4
  66. package/cli/production-auth.mjs +4 -2
  67. package/cli/production-mail.mjs +1 -1
  68. package/cli/project.mjs +2 -0
  69. package/cli/rehearse/options.mjs +3 -3
  70. package/cli/release-candidate.mjs +2 -2
  71. package/cli/release.mjs +5 -5
  72. package/cli/server-registry.mjs +3 -3
  73. package/cli/server-resources.mjs +1 -1
  74. package/cli/setup-input.mjs +6 -6
  75. package/cli/signin.mjs +11 -10
  76. package/cli/site-render.mjs +1 -1
  77. package/cli/size/schema.mjs +1 -1
  78. package/cli/size/verify-step.mjs +1 -1
  79. package/cli/transfers.mjs +4 -4
  80. package/edition-authoring/api-source.mjs +121 -0
  81. package/edition-authoring/archive-source.mjs +1 -86
  82. package/edition-authoring/base-copies.mjs +5 -3
  83. package/global/CHANGELOG.md +31 -0
  84. package/global/cli/command.mjs +6 -5
  85. package/global/cli/install.mjs +6 -3
  86. package/global/cli/path-link.mjs +11 -22
  87. package/global/cli/repo-command.mjs +4 -3
  88. package/global/cli/repository-contract.mjs +3 -3
  89. package/global/door/command.mjs +39 -38
  90. package/global/door/control.mjs +3 -3
  91. package/global/door/pages.mjs +6 -5
  92. package/global/door/server.mjs +8 -5
  93. package/global/door/sites.mjs +14 -13
  94. package/global/launch/capacity.mjs +2 -2
  95. package/global/launch/dev.mjs +6 -6
  96. package/global/launch/door.mjs +1 -1
  97. package/global/launch/facts.mjs +2 -2
  98. package/global/launch/failure.mjs +1 -1
  99. package/global/launch/prepare.mjs +3 -3
  100. package/global/launch/render.mjs +3 -2
  101. package/global/launch/worker.mjs +1 -1
  102. package/global/list.mjs +4 -4
  103. package/global/main.mjs +32 -31
  104. package/global/registry.mjs +1 -1
  105. package/global/run.mjs +4 -4
  106. package/global/update/command.mjs +5 -5
  107. package/global/update/notice.mjs +1 -1
  108. package/global/version.mjs +1 -1
  109. package/install.sh +17 -4
  110. package/modules/deploy-kit/README.md +10 -3
  111. package/modules/deploy-kit/asset-health.mjs +6 -4
  112. package/modules/deploy-kit/cancellation.mjs +26 -0
  113. package/modules/deploy-kit/d1-import-diagnostics.mjs +3 -2
  114. package/modules/deploy-kit/deploy.mjs +8 -3
  115. package/modules/deploy-kit/diagnostics.mjs +11 -4
  116. package/modules/deploy-kit/health-request.mjs +16 -9
  117. package/modules/deploy-kit/health.mjs +14 -11
  118. package/modules/deploy-kit/owner-cli.mjs +49 -21
  119. package/modules/deploy-kit/owner-remove.mjs +7 -6
  120. package/modules/deploy-kit/owner-secret.mjs +7 -4
  121. package/modules/deploy-kit/owner.mjs +46 -28
  122. package/modules/deploy-kit/provider-transport.mjs +2 -0
  123. package/modules/deploy-kit/provider.mjs +10 -9
  124. package/modules/deploy-kit/readiness-window.mjs +5 -3
  125. package/modules/deploy-kit/site.mjs +1 -1
  126. package/modules/deploy-kit/teardown.mjs +5 -4
  127. package/modules/operator-auth/dev/index.mjs +4 -3
  128. package/modules/operator-auth/dev/sign-in-as.mjs +2 -1
  129. package/modules/operator-auth/dev-gate.mjs +3 -2
  130. package/modules/operator-auth/routes.mjs +2 -1
  131. package/modules/operator-auth/terminal-guidance.mjs +3 -0
  132. package/onboarding/adapter-settings.mjs +1 -0
  133. package/onboarding/adapter.mjs +3 -3
  134. package/onboarding/agent-handoff.mjs +1 -1
  135. package/onboarding/busy.mjs +1 -1
  136. package/onboarding/launcher.mjs +1 -1
  137. package/onboarding/local/environment.mjs +1 -1
  138. package/onboarding/local/operation.mjs +12 -4
  139. package/onboarding/local/owner.mjs +2 -2
  140. package/onboarding/operator-installer.mjs +4 -3
  141. package/onboarding/operator-migrations.mjs +1 -1
  142. package/onboarding/operator-prerequisites.mjs +26 -14
  143. package/onboarding/operator-settings.mjs +28 -0
  144. package/onboarding/process-diagnostics.mjs +2 -2
  145. package/onboarding/project-vite.mjs +1 -1
  146. package/package.json +1 -1
@@ -31,11 +31,11 @@ export async function prepare({ root, args, setupArgs = [], env, report, directo
31
31
  // pinned package's verbs.
32
32
  let installed = false;
33
33
  if (pinnedPackage(root)?.ready === false) {
34
- if (doorStart) throw new LaunchFailure(3, `${root} is not installed, and the front door starts only prepared checkouts. Run rer dev in it once.`);
34
+ if (doorStart) throw new LaunchFailure(3, `${root} is not installed, and the front door starts only prepared checkouts. Run ~/.local/bin/rer dev in it once.`);
35
35
  const current = await pinPolicy(root, 'package');
36
36
  report({ phase: 'check', message: 'checking the server limit' });
37
37
  const capacity = await checkCapacity(await realpath(root), { ...env, ...personEnvironment(env, args, current) }, current);
38
- if (capacity.own) throw new LaunchFailure(3, `A server of ${root} is running, but its node_modules lacks the rer version it pins. Stop it with rer dev --stop, then run rer dev again.`);
38
+ if (capacity.own) throw new LaunchFailure(3, `A server of ${root} is running, but its node_modules lacks the rer version it pins. Stop it with ~/.local/bin/rer dev --stop, then run ~/.local/bin/rer dev again.`);
39
39
  report({ phase: 'install', message: 'installing dependencies' });
40
40
  await recorded(directory, installState, () => installPinned(root, { env, output: text => log(text.trimEnd()), children, signal }));
41
41
  installed = true;
@@ -56,7 +56,7 @@ export async function prepare({ root, args, setupArgs = [], env, report, directo
56
56
  // Repository setup can supply the same owner/answer inputs as checkout setup.
57
57
  const extraSetup = setupArgs.filter((arg, i) => !['--json', '--non-interactive', '--port', '--host', '--door', '--owner-email'].includes(arg) && !['--port', '--host', '--owner-email'].includes(setupArgs[i - 1]));
58
58
  const ownerArgs = flagValue(setupArgs, '--owner-email') ? ['--owner-email', flagValue(setupArgs, '--owner-email')] : [];
59
- const unprepared = what => new LaunchFailure(3, `${checkout} is not ${what}, and the front door starts only prepared checkouts. Run rer dev in it once.`);
59
+ const unprepared = what => new LaunchFailure(3, `${checkout} is not ${what}, and the front door starts only prepared checkouts. Run ~/.local/bin/rer dev in it once.`);
60
60
  if (!installed && await needsInstall(root, await installState.read(directory))) {
61
61
  if (doorStart) throw unprepared('installed');
62
62
  report({ phase: 'install', message: 'installing dependencies' });
@@ -1,3 +1,4 @@
1
+ import { withCommandHelp } from '../../cli/command-guidance.mjs';
1
2
  import { humanError } from '../../cli/human-error.mjs';
2
3
  // What `rer dev` prints while it launches: a progress line at least every 30
3
4
  // seconds (a `progress` event with --json), then the dispatcher's ready lines.
@@ -24,7 +25,7 @@ export function printer({ json, stopHint, keyless = false, root }) {
24
25
  return {
25
26
  phase({ phase, message }) { if (phase !== 'note') { if (phase !== currentPhase) phaseStarted = Date.now(); currentPhase = phase; current = message; } progress(phase, message); },
26
27
  attaching(startedAt) { progress('attach', `attaching to the launch already preparing this checkout (started ${elapsed(Date.now() - startedAt)} ago)`); },
27
- heartbeat() { if (Date.now() - last >= quiet) progress('waiting', `still ${current} (${elapsed(Date.now() - phaseStarted)}). Allow up to 10 minutes; if this command is stopped, run rer dev again to reattach.`); },
28
+ heartbeat() { if (Date.now() - last >= quiet) progress('waiting', `still ${current} (${elapsed(Date.now() - phaseStarted)}). Allow up to 10 minutes; if this command is stopped, run ~/.local/bin/rer dev again to reattach.`); },
28
29
  // The dispatcher's ready event, as its own human ready lines.
29
30
  async ready(ready, { log, pid }) {
30
31
  if (keyless) { const { openUrl, ...rest } = ready; ready = rest; }
@@ -48,7 +49,7 @@ export function printer({ json, stopHint, keyless = false, root }) {
48
49
  if (ready.siteUrl) out.push(...(root ? [] : [`Site: ${ready.siteUrl}`]), `RER_SITE ${ready.siteUrl}`);
49
50
  out.push(`The server keeps running in the background${pid ? ` (PID ${pid})` : ''}. Stop it with: ${stopHint}`);
50
51
  if (log) out.push(`Server log (private): ${log}`);
51
- process.stdout.write(out.join('\n') + '\n');
52
+ process.stdout.write(withCommandHelp(out.join('\n')) + '\n');
52
53
  },
53
54
  failure(failure) {
54
55
  if (json) {
@@ -53,7 +53,7 @@ if (!await claimLaunch(directory, token)) {
53
53
  await events.write({ event: 'ready', ready: started.ready, pid, ...(ours ? { log: serverLog } : {}) });
54
54
  } catch (error) {
55
55
  log(String(error?.stack ?? error));
56
- const failure = workerFailure(stopping.signal.aborted ? new LaunchFailure(1, 'rer dev --stop stopped this launch before the app was ready.') : error, { root });
56
+ const failure = workerFailure(stopping.signal.aborted ? new LaunchFailure(1, '~/.local/bin/rer dev --stop stopped this launch before the app was ready.') : error, { root });
57
57
  await events.write({ event: 'failed', exitCode: failure.exitCode, message: failure.message, error: failure.event });
58
58
  } finally {
59
59
  await releaseLaunch(directory, token);
package/global/list.mjs CHANGED
@@ -11,7 +11,7 @@ import { checkoutFolders } from '../cli/checkout-folders.mjs';
11
11
 
12
12
  const run = promisify(execFile);
13
13
  const reasons = {
14
- independent: 'independent project: rer runs its declared commands; zero-setup rer dev applies to first-party seeds only',
14
+ independent: 'independent project: rer runs its declared commands; zero-setup ~/.local/bin/rer dev applies to first-party seeds only',
15
15
  unreadable: 'OPERATIONS.json cannot be read',
16
16
  };
17
17
 
@@ -39,9 +39,9 @@ async function entry(path, running) {
39
39
 
40
40
  export async function listCommand(args) {
41
41
  const json = args.includes('--json'), positional = args.filter(arg => arg !== '--json');
42
- if (positional.length > 1 || positional.some(arg => arg.startsWith('-'))) { process.stderr.write('Usage: rer list [DIR] [--json]\n'); return 2; }
42
+ if (positional.length > 1 || positional.some(arg => arg.startsWith('-'))) { process.stderr.write('Usage: ~/.local/bin/rer list [DIR] [--json]\n'); return 2; }
43
43
  let directory;
44
- try { directory = await realpath(resolve(positional[0] ?? '.')); } catch { process.stderr.write(`rer list: ${resolve(positional[0] ?? '.')} is not a folder.\n`); return 3; }
44
+ try { directory = await realpath(resolve(positional[0] ?? '.')); } catch { process.stderr.write(`~/.local/bin/rer list: ${resolve(positional[0] ?? '.')} is not a folder.\n`); return 3; }
45
45
  const running = new Map((await liveServers()).map(record => [record.checkout, record.url]));
46
46
  const folders = await checkoutFolders(directory);
47
47
  const checkouts = [];
@@ -51,6 +51,6 @@ export async function listCommand(args) {
51
51
  if (!checkouts.length) { process.stdout.write(`No checkouts with an OPERATIONS.json in ${directory}.\n`); return 0; }
52
52
  const width = Math.max(4, ...checkouts.map(item => item.name.length));
53
53
  const rows = checkouts.map(item => `${item.name.padEnd(width)} ${item.profile.padEnd(11)} ${(item.launchable ? 'yes' : 'no').padEnd(6)} ${(item.prepared === null ? '-' : item.prepared ? 'yes' : 'no').padEnd(8)} ${item.url ?? (item.launchable ? '-' : item.reason)}`);
54
- process.stdout.write([`${'NAME'.padEnd(width)} ${'PROFILE'.padEnd(11)} LAUNCH PREPARED URL`, ...rows, '', 'Launch one with: rer dev --cwd FOLDER'].join('\n') + '\n');
54
+ process.stdout.write([`${'NAME'.padEnd(width)} ${'PROFILE'.padEnd(11)} LAUNCH PREPARED URL`, ...rows, '', 'Launch one with: ~/.local/bin/rer dev --cwd FOLDER'].join('\n') + '\n');
55
55
  return 0;
56
56
  }
package/global/main.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { withCommandHelp } from '../cli/command-guidance.mjs';
1
2
  import { humanError } from '../cli/human-error.mjs';
2
3
  import { checkoutBootstrap, checkoutVerbs } from '../cli/contract.mjs';
3
4
  import { dispatcher, locate, pinnedPackage, unsupportedMessage } from './checkout.mjs';
@@ -8,11 +9,11 @@ import { repositoryCommands, repositoryHelp } from './cli/repository-contract.mj
8
9
  import { repoArguments } from './cli/repository.mjs';
9
10
  import { appSignInHelp } from '../cli/app-address.mjs';
10
11
 
11
- const help = `Usage: rer VERB [FLAGS]
12
+ const help = `Usage: ~/.local/bin/rer VERB [FLAGS]
12
13
 
13
- rer dev <repo> [--dir DIR] Clone, install, set up a local owner and start the app.
14
- rer setup <repo> [--dir DIR] Clone, install and set up, then stop.
15
- rer install <repo> [--dir DIR] Clone and install dependencies, then stop.
14
+ ~/.local/bin/rer dev <repo> [--dir DIR] Clone, install, set up a local owner and start the app.
15
+ ~/.local/bin/rer setup <repo> [--dir DIR] Clone, install and set up, then stop.
16
+ ~/.local/bin/rer install <repo> [--dir DIR] Clone and install dependencies, then stop.
16
17
  ${repositoryHelp}
17
18
 
18
19
  Inside a project (the nearest OPERATIONS.json at or above this folder, or --cwd DIR),
@@ -20,40 +21,40 @@ every verb runs that checkout's own pinned rer: the @runeditrun/rer version its
20
21
  pins (installed first for commands that run project code when node_modules holds another),
21
22
  else its vendored scripts/rer.mjs.
22
23
 
23
- rer dev Launch a first-party checkout with no setup steps: installs dependencies,
24
+ ~/.local/bin/rer dev Launch a first-party checkout with no setup steps: installs dependencies,
24
25
  sets up a local owner and a free port when needed, starts the app and prints
25
26
  RER_READY and a sign-in link. Without a terminal it returns once the app is
26
27
  ready and leaves it running (--detach and --foreground override); allow up
27
- to 10 minutes on a first launch, or rerun it to reattach. rer dev --stop stops it.
28
- rer rehearse [--cwd DIR] [--ref REF]
28
+ to 10 minutes on a first launch, or rerun it to reattach. ~/.local/bin/rer dev --stop stops it.
29
+ ~/.local/bin/rer rehearse [--cwd DIR] [--ref REF]
29
30
  Rehearse every managed build operation in a two-commit scratch copy.
30
- rer run SCRIPT [ARGS]
31
+ ~/.local/bin/rer run SCRIPT [ARGS]
31
32
  Run a package.json script with the pnpm and Node the checkout pins (rer keeps
32
- them off PATH): where a project's docs say pnpm run X, run rer run X.
33
- rer run --script FILE [ARGS]
33
+ them off PATH): where a project's docs say pnpm run X, run ~/.local/bin/rer run X.
34
+ ~/.local/bin/rer run --script FILE [ARGS]
34
35
  Run a downloaded JavaScript file with rer's Node, including its private runtime.
35
36
  Works outside a checkout; FILE is relative to here (or --cwd DIR).
36
- rer list [DIR] The checkouts in DIR (default: here), newest first, with whether rer dev can
37
+ ~/.local/bin/rer list [DIR] The checkouts in DIR (default: here), newest first, with whether ~/.local/bin/rer dev can
37
38
  launch them, whether they are set up, and their running URL. --json for data.
38
- rer business ... Set up your business once and share its name, logo and brand colour
39
- with apps that support Business. Start with rer business connect.
40
- rer companion ... Pair this computer with a Run Edit Run app and run its change requests here
41
- with your own Codex or Claude. rer companion --help lists the commands.
42
- rer door ... The opt-in front door: every checkout at http://NAME.localhost:PORT, started
43
- on its first visit and stopped when idle. rer door --help for its verbs.
44
- rer cli status This rer: version, contents digest, install channel, launcher and other rer
39
+ ~/.local/bin/rer business ... Set up your business once and share its name, logo and brand colour
40
+ with apps that support Business. Start with ~/.local/bin/rer business connect.
41
+ ~/.local/bin/rer companion ... Pair this computer with a Run Edit Run app and run its change requests here
42
+ with your own Codex or Claude. ~/.local/bin/rer companion --help lists the commands.
43
+ ~/.local/bin/rer door ... The opt-in front door: every checkout at http://NAME.localhost:PORT, started
44
+ on its first visit and stopped when idle. ~/.local/bin/rer door --help for its verbs.
45
+ ~/.local/bin/rer cli status This rer: version, contents digest, install channel, launcher and other rer
45
46
  commands on PATH. --json for data.
46
- rer cli install Install this package for the current user (~/.local/bin/rer).
47
- rer cli path Show the shell step that makes a bare rer work in new terminals.
48
- rer cli uninstall Remove the launcher and the install root; ~/.rer is untouched.
49
- rer update Move to the latest published rer (--version X for an exact one), the way it
47
+ ~/.local/bin/rer cli install Install this package for the current user (~/.local/bin/rer).
48
+ ~/.local/bin/rer cli path Show the shell step that makes a bare rer work in new terminals.
49
+ ~/.local/bin/rer cli uninstall Remove the launcher and the install root; ~/.rer is untouched.
50
+ ~/.local/bin/rer update Move to the latest published rer (--version X for an exact one), the way it
50
51
  was installed: npx and install.sh installs switch atomically, npm installs run npm.
51
- rer --version Print this rer's version; inside a checkout, also the version the checkout pins.
52
- rer queue NAME -- COMMAND [ARGS]
52
+ ~/.local/bin/rer --version Print this rer's version; inside a checkout, also the version the checkout pins.
53
+ ~/.local/bin/rer queue NAME -- COMMAND [ARGS]
53
54
  Run COMMAND once this computer's job queue admits it (heavy package scripts
54
55
  of a checkout that pins the rer package use it).
55
56
 
56
- Checkout verbs: ${Object.keys(checkoutVerbs).join(', ')}, listing. Run rer VERB --help in a checkout for its flags.
57
+ Checkout verbs: ${Object.keys(checkoutVerbs).join(', ')}, listing. Run ~/.local/bin/rer VERB --help in a checkout for its flags.
57
58
  ${appSignInHelp}
58
59
  `;
59
60
 
@@ -65,7 +66,7 @@ export async function main(argv) {
65
66
  if (verb === 'rehearse') return (await import('../cli/rehearse.mjs')).rehearseCommand(argv.slice(1));
66
67
  if (verb === '--version' || verb === '-v') return (await import('./version.mjs')).versionCommand(argv);
67
68
  if (verb === 'queue' && argv.length === 2 && argv[1] === '--help') {
68
- process.stdout.write('Usage: rer queue NAME -- COMMAND [ARGS]\nRun COMMAND once this computer\'s job queue admits it.\n');
69
+ process.stdout.write('Usage: ~/.local/bin/rer queue NAME -- COMMAND [ARGS]\nRun COMMAND once this computer\'s job queue admits it.\n');
69
70
  return 0;
70
71
  }
71
72
  // Only the zero-setup launch sets this, for its own setup child; an explicit
@@ -76,15 +77,15 @@ export async function main(argv) {
76
77
  if (verb === 'business') return (await import('../cli/business/command.mjs')).businessCommand(argv.slice(1));
77
78
  if (verb === 'companion') return (await import('../cli/companion/command.mjs')).companionCommand(argv.slice(1));
78
79
  const notice = await import('./update/notice.mjs');
79
- if (verb !== 'doctor' && notice.wantsNotice(argv)) await notice.updateNotice();
80
- if (!verb || verb === '--help' || verb === '-h' || verb === 'help') { process.stdout.write(help); return 0; }
80
+ if (verb !== 'doctor' && !(verb === 'cli' && argv[1] === 'path') && notice.wantsNotice(argv)) await notice.updateNotice();
81
+ if (!verb || verb === '--help' || verb === '-h' || verb === 'help') { process.stdout.write(withCommandHelp(help)); return 0; }
81
82
  if (verb === 'cli') return (await import('./cli/command.mjs')).cliCommand(argv.slice(1));
82
83
  if (verb === 'list') return (await import('./list.mjs')).listCommand(argv.slice(1));
83
84
  if (verb === 'door' && argv[1] !== 'clauses') return (await import('./door/command.mjs')).doorCommand(argv.slice(1));
84
85
  if (verb === 'run') return (await import('./run.mjs')).runScript(argv.slice(1));
85
86
  if (repositoryCommands[verb] && argv.includes('--help')) {
86
87
  const { help } = await import('../cli/parse.mjs');
87
- process.stdout.write(`${help(verb)}\n${repositoryCommands[verb].usage}\n${repositoryCommands[verb].effects}\n${repositoryHelp}`);
88
+ process.stdout.write(withCommandHelp(`${help(verb)}\n${repositoryCommands[verb].usage}\n${repositoryCommands[verb].effects}\n${repositoryHelp}`));
88
89
  return 0;
89
90
  }
90
91
  try {
@@ -127,7 +128,7 @@ export async function main(argv) {
127
128
  }
128
129
  if (verb === 'queue') {
129
130
  const [, name, separator, command] = argv;
130
- if (!name || separator !== '--' || !command) { process.stderr.write('Usage: rer queue NAME -- COMMAND [ARGS]\n'); return 2; }
131
+ if (!name || separator !== '--' || !command) { process.stderr.write('Usage: ~/.local/bin/rer queue NAME -- COMMAND [ARGS]\n'); return 2; }
131
132
  if (mode === 'package') return delegate(target, target.args);
132
133
  return (await import('../onboarding/queued-entry.mjs')).queuedCommandLine(argv.slice(1));
133
134
  }
@@ -146,7 +147,7 @@ export async function main(argv) {
146
147
  if (!(failure instanceof LaunchFailure)) throw failure;
147
148
  // A --json caller gets the failed step as data, as the checkout's own verbs report it.
148
149
  if (failure.event && target.args.includes('--json')) for (const event of [{ ...failure.event, verb }, { version: 1, verb, event: 'result', ok: false, exitCode: failure.exitCode }]) process.stdout.write(JSON.stringify(event) + '\n');
149
- else process.stderr.write(humanError(failure, { retry: `rer ${verb} --cwd '${target.root.replaceAll("'", "'\\''")}'` }) + '\n');
150
+ else process.stderr.write(humanError(failure, { retry: `~/.local/bin/rer ${verb} --cwd '${target.root.replaceAll("'", "'\\''")}'` }) + '\n');
150
151
  return failure.exitCode;
151
152
  }
152
153
  }
@@ -21,4 +21,4 @@ export async function liveServers(env = process.env) {
21
21
  return live;
22
22
  }
23
23
 
24
- export const stopCommand = record => `rer ${record.mode} --stop --cwd ${JSON.stringify(record.checkout)}`;
24
+ export const stopCommand = record => `~/.local/bin/rer ${record.mode} --stop --cwd ${JSON.stringify(record.checkout)}`;
package/global/run.mjs CHANGED
@@ -10,11 +10,11 @@ import { delimiter, dirname, join, resolve } from 'node:path';
10
10
  import { locate } from './checkout.mjs';
11
11
  import { shared } from '../cli/shared.mjs';
12
12
 
13
- export const runUsage = `Usage: rer run [--cwd DIR] [SCRIPT [ARGS...]]
14
- rer run [--cwd DIR] --script FILE [ARGS...]
13
+ export const runUsage = `Usage: ~/.local/bin/rer run [--cwd DIR] [SCRIPT [ARGS...]]
14
+ ~/.local/bin/rer run [--cwd DIR] --script FILE [ARGS...]
15
15
  Runs a package.json script of this checkout as pnpm run SCRIPT ARGS would, with the
16
16
  pnpm and Node the checkout pins (rer keeps them off PATH). Without SCRIPT it lists
17
- the scripts. Where a project's docs say pnpm run X -- ARGS, run rer run X -- ARGS.
17
+ the scripts. Where a project's docs say pnpm run X -- ARGS, run ~/.local/bin/rer run X -- ARGS.
18
18
  With --script, runs a JavaScript file with the Node running rer, including the
19
19
  installer's private runtime. No checkout or package manager is needed. FILE is
20
20
  relative to the current folder (or --cwd DIR); remaining arguments go to the file.
@@ -49,7 +49,7 @@ export async function runScript(args) {
49
49
  }
50
50
  const target = locate(cwd ? ['run', '--cwd', cwd] : ['run']);
51
51
  if (!target.root || !['first-party', 'independent'].includes(target.profile)) {
52
- process.stderr.write(`rer run runs inside a checkout: a folder with OPERATIONS.json at or above this one, or --cwd DIR.\n`);
52
+ process.stderr.write(`~/.local/bin/rer run runs inside a checkout: a folder with OPERATIONS.json at or above this one, or --cwd DIR.\n`);
53
53
  return 2;
54
54
  }
55
55
  let scripts = {};
@@ -15,7 +15,7 @@ import { ownManifest, ownRoot, packageDigest, packageName } from '../package-inf
15
15
  import { readPackage, writePackage } from './archive.mjs';
16
16
  import { compareVersions, packageMetadata, pickRelease, registryUrl, UpdateFailure } from './registry.mjs';
17
17
 
18
- const usage = 'Usage: rer update [--version X]\n';
18
+ const usage = 'Usage: ~/.local/bin/rer update [--version X]\n';
19
19
 
20
20
  function parse(args) {
21
21
  if (!args.length) return {};
@@ -60,14 +60,14 @@ async function npmGlobal(version) {
60
60
 
61
61
  export async function update(args) {
62
62
  const options = parse(args);
63
- if (!options) { process.stderr.write(`Unsupported: rer update ${args.join(' ')}\n${usage}`); return 2; }
63
+ if (!options) { process.stderr.write(`Unsupported: ~/.local/bin/rer update ${args.join(' ')}\n${usage}`); return 2; }
64
64
  const { channel } = await channelOf(layout()), current = ownManifest().version;
65
- if (channel === 'source') { process.stderr.write(`This rer runs from a source checkout (${ownRoot}), which rer update does not change. Update the checkout with git, or install rer with: npx -y ${packageName} cli install\n`); return 1; }
65
+ if (channel === 'source') { process.stderr.write(`This rer runs from a source checkout (${ownRoot}), which ~/.local/bin/rer update does not change. Update the checkout with git, or install rer with: npx -y ${packageName} cli install\n`); return 1; }
66
66
  const work = await mkdtemp(join(tmpdir(), 'rer-update-'));
67
67
  try {
68
68
  const release = pickRelease(await packageMetadata(), options.version);
69
69
  if (!options.version && compareVersions(current, release.version) > 0) {
70
- process.stdout.write(`rer ${current} is newer than the latest published version (${release.version}); nothing changed. rer update --version ${release.version} installs that one.\n`);
70
+ process.stdout.write(`rer ${current} is newer than the latest published version (${release.version}); nothing changed. ~/.local/bin/rer update --version ${release.version} installs that one.\n`);
71
71
  return 0;
72
72
  }
73
73
  // The same version counts as current only with the same contents: a
@@ -85,7 +85,7 @@ export async function update(args) {
85
85
  return await run(process.execPath, [join(work, 'package/global/rer.mjs'), 'cli', 'install'], { ...process.env, RER_INSTALL_CHANNEL: channel, RER_INSTALL_NO_NEXT: '1' });
86
86
  } catch (error) {
87
87
  if (!(error instanceof UpdateFailure)) throw error;
88
- process.stderr.write(`rer update: ${error.message} rer ${current} is still selected.\n`);
88
+ process.stderr.write(`~/.local/bin/rer update: ${error.message} rer ${current} is still selected.\n`);
89
89
  return 1;
90
90
  } finally { await rm(work, { recursive: true, force: true }); }
91
91
  }
@@ -29,7 +29,7 @@ export async function updateNotice(env = process.env) {
29
29
  await writeFile(file, JSON.stringify({ checkedAt: Date.now() }) + '\n');
30
30
  const latest = await latestVersion(env);
31
31
  const current = ownManifest().version;
32
- if (latest && compareVersions(latest, current) > 0) process.stderr.write(`rer ${latest} is available (this is ${current}). Update with: rer update\n`);
32
+ if (latest && compareVersions(latest, current) > 0) process.stderr.write(`rer ${latest} is available (this is ${current}). Update with: ~/.local/bin/rer update\n`);
33
33
  } catch {
34
34
  // The notice never stands in the way of the command.
35
35
  }
@@ -14,7 +14,7 @@ export async function versionCommand(argv) {
14
14
  if (pinned) {
15
15
  process.stdout.write(pinned.ready
16
16
  ? `This checkout (${target.root}) pins rer ${pinned.installed} (package).\n`
17
- : `This checkout (${target.root}) pins rer ${pinned.declared} (package), ${pinned.installed ? `but node_modules holds ${pinned.installed}` : 'not installed yet'}: run rer install.\n`);
17
+ : `This checkout (${target.root}) pins rer ${pinned.declared} (package), ${pinned.installed ? `but node_modules holds ${pinned.installed}` : 'not installed yet'}: run ~/.local/bin/rer install.\n`);
18
18
  return 0;
19
19
  }
20
20
  const { mode, entry } = dispatcher(target.root);
package/install.sh CHANGED
@@ -156,9 +156,9 @@ NODE
156
156
  no_next=
157
157
  if [ "$#" -gt 0 ]; then no_next=1; fi
158
158
  RER_INSTALL_CHANNEL=script RER_INSTALL_NO_NEXT=$no_next "$node_binary" "$work/stage/package/global/rer.mjs" cli install </dev/null \
159
- || fail "rer cli install failed; any previous install is still selected."
159
+ || fail "~/.local/bin/rer cli install failed; any previous install is still selected."
160
160
  if [ "$#" -eq 0 ]; then
161
- printf 'For Business setup: %s business setup --help\n' "$HOME/.local/bin/rer"
161
+ printf 'For Business setup: ~/.local/bin/rer business setup --help\n'
162
162
  return
163
163
  fi
164
164
  # The command can tell the person how to run rer again from their own shell,
@@ -179,10 +179,23 @@ NODE
179
179
  status=0
180
180
  "$HOME/.local/bin/rer" "$@" || status=$?
181
181
  if [ "$1" != business ]; then
182
- printf 'Run a downloaded JavaScript tool with the installed runtime: "%s/.local/bin/rer" run --script ./tool.mjs [ARGS...]\n' "$HOME"
182
+ printf 'Run a downloaded JavaScript tool with the installed runtime: ~/.local/bin/rer run --script ./tool.mjs [ARGS...]\n'
183
+ printf "%s\n" "If you see 'command not found', run \`~/.local/bin/rer cli path\` and paste the line it prints."
183
184
  fi
184
185
  if [ -n "$path_step" ]; then
185
- printf '\nRequired next step: %s/.local/bin is not on your PATH, so a bare `rer` in a new terminal says "rer: command not found". Run this in the terminal you will use, and add the same line to your shell startup file (~/.zshrc for zsh, ~/.bashrc for bash):\n export PATH="$HOME/.local/bin:$PATH"\nOther shells, such as fish: run %s/.local/bin/rer cli path to see the line for yours. Until then, start rer with %s/.local/bin/rer. This installer changes no shell file.\n' "$HOME" "$HOME" "$HOME"
186
+ shell_name=${SHELL:-}
187
+ case "${shell_name##*/}" in
188
+ zsh) shell_file='~/.zshrc' ;;
189
+ bash) shell_file='~/.bashrc' ;;
190
+ fish) shell_file='fish user path configuration' ;;
191
+ *) shell_file='this terminal only' ;;
192
+ esac
193
+ printf '\nRequired next step: run the line below; you add ~/.local/bin to PATH in %s. The installer changes no shell file.\n' "$shell_file"
194
+ "$HOME/.local/bin/rer" cli path
195
+ fi
196
+ if [ "$1" != business ]; then
197
+ shell_name=${SHELL:-}
198
+ case "${shell_name##*/}" in zsh|bash) printf 'Open a new Terminal window, then `rer` works by name.\n' ;; esac
186
199
  fi
187
200
  return "$status"
188
201
  }
@@ -96,17 +96,17 @@ A declaration may also bind another owner-deployed Worker and may keep its own w
96
96
 
97
97
  A service's Worker name is derived from its `project` and this deploy's environment, so the example above binds `egress-service-production`. `allowedHosts` becomes the binding's `props` (`{allowedHosts}`), which the bound Worker reads as `ctx.props`. The binding is uploaded and read back like every other binding, so a changed `props` is reported as `binding-readback-mismatch`. Before any write, deploy reads each bound Worker. If it is absent, deploy refuses with `service-worker-missing` and resource `service:<worker>`; deploy that Worker first. `workersDev: false` keeps the route off: an enabled route is switched off on upload, the receipt's `origin` is `null`, and health uses provider readback only, because there is no public `/health` to request. [modules/egress-service](https://github.com/runeditrun/base/blob/main/modules/egress-service/README.md) is the Worker this exists for.
98
98
 
99
- `ownerTarget`, `ownerPlan`, `ownerDeploy` and `ownerHealth` (exported from `index.mjs`) are the same steps for a seed's own script. A seed script can compute vars before calling `ownerPlan`.
99
+ `ownerTarget`, `ownerPlan`, `ownerDeploy` and `ownerHealth` (exported from `index.mjs`) are the same steps for a seed's own script. A seed script can compute vars before calling `ownerPlan`. Pass `statePath` to `ownerTarget` to resolve an existing deployment's recorded Worker; without a record it derives `<project>-<environment>` as before. The owner CLI uses that recorded name for owner finalization, redeploy, secret changes, health, sign-in and removal, including native uploaders that resolve a custom resource prefix. The record must still match the supplied account, project and environment, and provider identity checks still refuse a replaced Worker. A target mismatch names the recorded and requested Workers; use the original checkout, account and environment, or a new environment for a separate deployment.
100
100
 
101
101
  Ownership lives in a state file, by default `.rer/deploy/<environment>.json` under the checkout (mode 0600). It holds the account, project, environment, the resources this kit created with their ids (for an R2 bucket, its creation date), the pending upload intent and its observed provider identity, and the last receipt. It holds no secret values. Keep it out of Git and keep it: it is the only proof of which resources the kit created. Back it up after each deploy; see "If the state file is lost" below.
102
102
 
103
103
  - **Find or create.** Before any write, the kit lists every declared kind and checks the Worker. A name it created is reused. An absent name is created. A same-named resource it did not create is refused with `resource-name-collision` and the resource name; it is never adopted. Ownership collisions, missing first-deploy secrets and existing Cron drift fail before the first provider write. Provider failures may interrupt later writes; see partial failure and resume below.
104
104
  - **Re-run.** The same build writes nothing: no create, upload, migration, trigger or secret write, and the state file stays byte-identical. A later release that declares a new resource creates only that resource.
105
- - **Partial failure and resume.** The kit records each create as `pending` before the request and `created` with the provider id after it. A failed create leaves `pending`. On the next run an absent pending name is created again, and a present one is refused as `uncertain-resource-create`, because a lost response cannot prove who created it. Inspect it: if it is the empty resource from the interrupted run, delete it and re-run. A Worker upload is recorded as created when the upload succeeds, so a failure after it resumes with one fresh upload. If the response to the very first upload is lost, the Worker exists but is still `pending`. The kit records the upload's fingerprint before sending it. When an upload's response or its readback is lost (a first upload or a redeploy), the next run accepts the live version as this deploy's own only when it carries that fingerprint both as its `RER_DEPLOY_FINGERPRINT` binding and as its `rer-deploy:<fingerprint>` annotation: it records the live version id, deployment id and etag, then resumes with one fresh upload. Any other live version is refused, as `uncertain-resource-create` with no prior receipt and as `owned-resource-replaced` with one. If the uncertain Worker cannot be authenticated, inspect it and delete it only after confirming that it is the kit-created Worker and that its Durable Object data is disposable. Back up any needed data before deleting it. Migration claims keep the rules under Migration safety.
105
+ - **Partial failure and resume.** The kit records each create as `pending` before the request and `created` with the provider id after it. A failed create leaves `pending`. On the next run an absent pending name is created again, and a present one is refused as `uncertain-resource-create`, because a lost response cannot prove who created it. The command names the resource it found and preserves both it and the deployment record, without adopting, deleting or creating a duplicate. This is an ownership boundary: the current create interface has no durable request identifier that a later listing can corroborate. Inspect it: if it is the empty resource from the interrupted run, delete it and re-run. A Worker upload is recorded as created when the upload succeeds. After an interruption, the next run finishes an authenticated matching upload without creating another code version. Partial content-addressed asset uploads restart through a new upload session. If the response to the very first upload is lost, the Worker exists but is still `pending`. The kit records the upload's fingerprint before sending it. When an upload's response or its readback is lost (a first upload or a redeploy), the next run accepts the live version as this deploy's own only when it carries that fingerprint both as its `RER_DEPLOY_FINGERPRINT` binding and as its `rer-deploy:<fingerprint>` annotation: it records the live version id, deployment id and etag, then completes routing, triggers, receipt and health for that version. If the requested build changed, it uploads that new build instead. Any other live version is refused, as `uncertain-resource-create` with no prior receipt and as `owned-resource-replaced` with one. If the uncertain Worker cannot be authenticated, inspect it and delete it only after confirming that it is the kit-created Worker and that its Durable Object data is disposable. Back up any needed data before deleting it. Migration claims keep the rules under Migration safety.
106
106
  - **Drift.** A created resource that has gone is refused as `owned-resource-missing`; one replaced under the same name is refused as `owned-resource-replaced`. The kit never deletes or recreates them. This covers D1, KV, Queues and R2 (a bucket is identified by its creation date; a state file written before that was recorded keeps working and is not checked for that bucket). For the Worker, the live deployment (version id, deployment id and etag) must be the last receipt's before any write; someone else's upload under the same name is refused as `owned-resource-replaced` and never overwritten. Immediately before the Worker PUT, the kit rechecks every saved resource identity, including resources omitted from the current plan, then the Worker identity. A replacement during provisioning or asset upload is refused before the upload intent or receipt is saved. An interrupted successful upload may resume only when the live version id, deployment id and etag match the identity saved immediately after that upload, or, when its readback was lost before that identity was saved, when the live version carries the fingerprint saved immediately before that upload (binding and annotation). A receipt's historical fingerprint never overrides a receipt mismatch.
107
107
  - **Lost upgrade response.** An interrupted upload can resume when its saved upload intent authenticates the live version by the pending fingerprint binding and annotation, or by its saved provider identity. Otherwise deployment refuses the mismatch. A [Cloudflare rollback](https://developers.cloudflare.com/workers/versions-and-deployments/rollbacks/) creates a new deployment, so it does not restore the recorded identity.
108
108
  - **Settling listings.** Right after a create or delete, an account listing can briefly disagree with its own page counts (`provider-partial-list`: on 13 October 2026 D1's `total_count` lagged its rows by about 7 seconds after a create). Owner-mode deploy, health, removal, secret changes and sign-in discard such a snapshot and list again from the start for up to 120 seconds with a short backoff; a partial listing is never accepted. The same applies to the GET reads of a Worker's deployments and versions that settle a pending secret change.
109
- - **One run at a time.** A deploy takes an exclusive lock file, `<state file>.lock`, for the whole run and removes it at the end, even after a failure. A second run on the same state file is refused as `owner-state-locked` before any provider request. If a run was killed (power loss, `kill -9`) and no deploy is running, delete the lock file by hand.
109
+ - **One run at a time.** A deploy takes an exclusive lock file, `<state file>.lock`, for the whole run and removes it at the end, even after a failure. A concurrent run on the same state file is refused as `owner-state-locked` before any provider request. Locks record PID and process start identity. A new run automatically takes over a dead writer's lock using the same exclusive takeover guard as local operations; a live writer remains protected. Legacy PID-only deploy locks are also recovered when that PID is gone. After a grant expiry stop, repeat the same `rer deploy` under a fresh grant with the same checkout, account and environment; retained resource identities, migrations, owner claim and secret retirement continue from their saved state.
110
110
 
111
111
  The CLI prints JSON: refusal codes and resource names only, never inputs, tokens or provider bodies.
112
112
  A refused provider call also carries `providerRefusal` on the thrown error: the call (`PUT /workers/scripts/<name>`) and Cloudflare's own codes and messages, with the account id and token removed and each message cut to 300 characters. `rer deploy` names it when a custom deploy hook fails on one.
@@ -544,3 +544,10 @@ tokens should be left unset so rer issues a fresh one. The existing owner is
544
544
  kept, and a successful claim retires the one-time token. A hook that fails
545
545
  without an HTTP exchange can only supply its own cause. Seeds copy this guide
546
546
  and `RUN-LOCALLY.md` for these recovery instructions.
547
+
548
+ The owner CLI accepts an AbortSignal as `signal` in its options. The public
549
+ `rer deploy` passes its lifecycle signal through provider requests and response
550
+ reads, health checks, polling waits and owned Git processes. Cancellation retains
551
+ the deployment record and releases its lock before returning. SIGTERM exits
552
+ `rer deploy` with status 143 (SIGINT: 130); a new granted command can resume with
553
+ a fresh credential. Unconfirmed creates retain their ownership uncertainty.
@@ -1,18 +1,20 @@
1
+ import { pause, combinedSignal } from './cancellation.mjs';
1
2
  import { nameAssetFailure } from './diagnostics.mjs';
2
3
 
3
4
  /** Probe a real built file after identity health. A transient read gets one replay;
4
5
  * a fresh edge missing a hashed file may settle within the existing route window. */
5
- export async function servedAsset(origin, path, request, timeoutMs, {window, windowMs = 0, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))} = {}) {
6
+ export async function servedAsset(origin, path, request, timeoutMs, {window, windowMs = 0, clock = () => performance.now(), sleep, signal} = {}) {
6
7
  const start = clock(), budget = Math.min(windowMs || timeoutMs, window?.remaining() ?? Infinity);
7
- const deadline = AbortSignal.timeout(Math.max(1, Math.ceil(budget)));
8
+ const deadline = combinedSignal(signal,AbortSignal.timeout(Math.max(1, Math.ceil(budget))));
8
9
  let transient = 0, failure;
9
10
  const fail = (code, status) => nameAssetFailure(new Error(code), [path], status);
10
11
  for (;;) {
12
+ signal?.throwIfAborted();
11
13
  const remaining = Math.min(budget - (clock() - start), window?.remaining() ?? Infinity);
12
14
  if (remaining <= 0 || deadline.aborted) throw failure ?? fail('asset-readiness-timeout');
13
15
  let response;
14
16
  try { response = await request(`${origin}/${path.split('/').map(encodeURIComponent).join('/')}`, {redirect:'manual',signal:AbortSignal.any([deadline,AbortSignal.timeout(Math.max(1, Math.ceil(Math.min(timeoutMs,remaining / (transient ? 1 : 2)))))]),headers:{'Cache-Control':'no-cache'}}); }
15
- catch { failure = fail('asset-transport-failed'); }
17
+ catch { signal?.throwIfAborted(); failure = fail('asset-transport-failed'); }
16
18
  if (response) {
17
19
  await response.body?.cancel().catch(() => {});
18
20
  if (response.status === 200 && !response.redirected) return {path,status:200};
@@ -23,6 +25,6 @@ export async function servedAsset(origin, path, request, timeoutMs, {window, win
23
25
  if (!propagating && (++transient > 1 || response?.status === 404)) throw failure;
24
26
  const rest = Math.min(budget - (clock() - start), window?.remaining() ?? Infinity);
25
27
  if (rest <= 0 || deadline.aborted) throw failure;
26
- await sleep(Math.min(2000,rest));
28
+ await pause(Math.min(2000,rest),signal,sleep);
27
29
  }
28
30
  }
@@ -0,0 +1,26 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+
3
+ export const combinedSignal = (...signals) => {
4
+ const present = signals.filter(Boolean);
5
+ return present.length > 1 ? AbortSignal.any(present) : present[0];
6
+ };
7
+
8
+ /** Waits finish before their caller releases its state lock. */
9
+ export async function pause(milliseconds, signal, sleep) {
10
+ signal?.throwIfAborted();
11
+ if (sleep) await sleep(milliseconds, {signal});
12
+ else await delay(milliseconds, undefined, {signal});
13
+ signal?.throwIfAborted();
14
+ }
15
+
16
+ /** Cancel the stream itself, so an in-flight read settles before unwinding. */
17
+ export async function readChunk(reader, signal) {
18
+ signal?.throwIfAborted();
19
+ const cancel = () => { void reader.cancel().catch(() => {}); };
20
+ signal?.addEventListener('abort', cancel, {once:true});
21
+ try {
22
+ const chunk = await reader.read();
23
+ signal?.throwIfAborted();
24
+ return chunk;
25
+ } finally { signal?.removeEventListener('abort', cancel); }
26
+ }
@@ -1,14 +1,15 @@
1
+ import { readChunk } from './cancellation.mjs';
1
2
  import { transportReason } from './provider-transport.mjs';
2
3
 
3
4
  // Import replies only need a bounded diagnostic prefix. A large refusal must
4
5
  // keep its HTTP status rather than becoming a generic response-size failure.
5
- export async function importResponseText(response, onReadError) {
6
+ export async function importResponseText(response, onReadError, signal) {
6
7
  if (!response.body) return '';
7
8
  const reader = response.body.getReader(), chunks = []; let length = 0;
8
9
  try {
9
10
  while (length < 64 * 1024) {
10
11
  let part;
11
- try { part = await reader.read(); } catch (cause) { throw onReadError(cause); }
12
+ try { part = await readChunk(reader,signal); } catch (cause) { throw onReadError(cause); }
12
13
  if (part.done) break;
13
14
  const bytes = part.value.subarray(0,64 * 1024-length);
14
15
  chunks.push(bytes); length += bytes.length;
@@ -18,7 +18,7 @@ import { verifyHealth } from './health.mjs';
18
18
  * passes the declaration's, so retiring the spent setup token leaves the build unchanged.
19
19
  * `locked`: the caller holds the install's deploy lock (owner mode), so migrate may retry a
20
20
  * claim on bytes a reviewed rewrite replaced. */
21
- export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,repeatOnly=false,createResources=!previousReceipt,uploadWithoutReceipt=false,onReceipt,onHealth,readiness={},env={},fetch=globalThis.fetch,healthOptions={},declaredSecrets=plan.secrets,locked=false}) {
21
+ export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,pendingUpload,repeatOnly=false,createResources=!previousReceipt,uploadWithoutReceipt=false,onReceipt,onHealth,readiness={},env={},fetch=globalThis.fetch,healthOptions={},declaredSecrets=plan.secrets,locked=false}) {
22
22
  validatePlan(plan); validateArtifact(artifact);
23
23
  await verifyServiceGrants(api, plan);
24
24
  for (const item of plan.d1) validateMigrations(item.migrations);
@@ -47,10 +47,15 @@ export async function deploy({api,plan,artifact,artifactSha256,previousReceipt,r
47
47
  // A migration failure names its database, so the owner knows which one to inspect.
48
48
  for (const item of plan.d1) migrations.push({binding:item.binding,...await migrate(api,resources.d1.find(x => x.binding === item.binding).id,item.migrations,{apply:!unchanged,upgrade:true,locked}).catch(error => { error.resource ??= `d1:${item.name}`; throw error; })});
49
49
  const window = readiness.window ?? readinessWindow({...(healthOptions.now ? {clock:healthOptions.now} : {}), ...(healthOptions.sleep ? {sleep:healthOptions.sleep} : {}), ...readiness});
50
+ // Owner mode already authenticated this pending version against its saved
51
+ // intent. Finish its routing/triggers/receipt instead of publishing it twice.
52
+ const resumedUpload = pendingUpload?.fingerprint === fingerprint && existing
53
+ && pendingUpload.provider?.versionId === existing.versionId && pendingUpload.provider?.deploymentId === existing.deploymentId
54
+ && pendingUpload.provider?.etag === existing.etag && existing.version?.annotations?.['workers/message'] === `rer-deploy:${fingerprint}`;
50
55
  let upload;
51
- if (!unchanged) { window.start(); upload = await uploadWorker(api,{plan,artifact,bindings,secrets,migration,fingerprint}); }
56
+ if (!unchanged) { window.start(); if (!resumedUpload) upload = await uploadWorker(api,{plan,artifact,bindings,secrets,migration,fingerprint}); }
52
57
  if (!unchanged) api = readinessAPI(api, window);
53
- const published = unchanged ? existing : await uploadedWorker({api,worker:plan.worker,upload,previous:existing,fingerprint,window}); assert(published,'missing-deployed-worker');
58
+ const published = unchanged || resumedUpload ? existing : await uploadedWorker({api,worker:plan.worker,upload,previous:existing,fingerprint,window}); assert(published,'missing-deployed-worker');
54
59
  verifyBindings(published.settings.bindings,bindings);
55
60
  verifyScheduledHandler(published,plan);
56
61
  // Finish routing activation before applying schedules to this deployment.
@@ -3,6 +3,13 @@ import { importFailureText, importText } from './d1-import-diagnostics.mjs';
3
3
  // Provider text is private until the CLI's existing credential redactor approves
4
4
  // it. Identity, rather than mutable Error properties, carries this diagnostic.
5
5
  const failures = new WeakMap();
6
+ /** Ownership refusals name safe resource identities, never account credentials. */
7
+ export function ownerTargetFailure(error) {
8
+ const mismatch = error?.ownerTargetMismatch;
9
+ if (error?.message !== 'owner-state-target-mismatch' || !mismatch) return undefined;
10
+ const name = value => typeof value === 'string' && /^[a-z][a-z0-9-]{2,62}$/.test(value) ? value : '(invalid Worker name)';
11
+ return `owner-state-target-mismatch: the deployment record names Worker ${name(mismatch.recordedWorker)}, while the requested deployment names Worker ${name(mismatch.requestedWorker)}. The record does not belong to this account, project, environment or Worker. Use the checkout, Cloudflare account and --environment that created this deployment, or choose a new --environment for a separate deployment. Nothing was changed.`;
12
+ }
6
13
  export function recordDeployFailure(error, details) {
7
14
  failures.set(error,{...failures.get(error),...details});
8
15
  return error;
@@ -14,13 +21,13 @@ export function deployDiagnostic(error, redact) {
14
21
  const failureCode = detail.code ?? error.message;
15
22
  const code = /^[a-zA-Z0-9_-]{1,120}$/.test(failureCode) ? clean(failureCode) : 'deploy-failed';
16
23
  return {code,step:clean(detail.step ?? 'deploy'),created:(detail.created ?? []).map(clean),
17
- ...(detail.providerRequest ? {providerRequest:{...detail.providerRequest,endpoint:clean(detail.providerRequest.endpoint),step:clean(detail.step ?? 'deploy'),body:redact ? providerText(detail.output ?? '',redact) : '(provider output withheld; rer deploy provides redacted details)'}} : {}),
24
+ ...(detail.providerRequest ? {providerRequest:{...detail.providerRequest,endpoint:clean(detail.providerRequest.endpoint),step:clean(detail.step ?? 'deploy'),body:redact ? providerText(detail.output ?? '',redact) : '(provider output withheld; ~/.local/bin/rer deploy provides redacted details)'}} : {}),
18
25
  ...(typeof error.resource==='string' && /^(?:d1|r2|kv|queues|worker|service):[a-z0-9-]+$/.test(error.resource) ? {resource:clean(error.resource)} : {}),
19
26
  ...(detail.providerCodes?.length ? {providerCodes:detail.providerCodes} : {}),
20
27
  ...(error.d1Import ? {d1Import:{...error.d1Import,body:importText(error.d1Import.body,redact),
21
28
  errors:error.d1Import.errors.map(item => ({...item,...(item.message ? {message:importText(item.message,redact,300)} : {})}))}} : {}),
22
29
  ...(redact && providerFailure(error,redact) ? {provider:providerFailure(error,redact)} : {}),
23
- output:(detail.output ? (redact ? clean(detail.output) : '(provider output withheld; rer deploy provides redacted details)') : '(no provider output)').split(/\r?\n/).slice(0,8).map(line=>line.slice(0,500)).join('\n')};
30
+ output:(detail.output ? (redact ? clean(detail.output) : '(provider output withheld; ~/.local/bin/rer deploy provides redacted details)') : '(no provider output)').split(/\r?\n/).slice(0,8).map(line=>line.slice(0,500)).join('\n')};
24
31
  }
25
32
  // Reuse the D1 upload retention boundary: redact complete text, omit URLs,
26
33
  // then bound UTF-8 bytes so a credential cannot straddle the public excerpt.
@@ -44,7 +51,7 @@ export function providerRefusal(error, redact = String) {
44
51
  /** What a migration that failed or stays refused means for the next run, from the
45
52
  * error's own `migration` or `migrationClaim` (set by any copy of the kit) and its
46
53
  * `d1:<name>` resource; undefined otherwise. */
47
- export function migrationFailure(error, again = 'rer deploy') {
54
+ export function migrationFailure(error, again = '~/.local/bin/rer deploy') {
48
55
  const safe = value => String(value).replace(/[^\w. -]/g,'?').slice(0,120);
49
56
  const database = /^d1:([a-z0-9-]+)$/.exec(error?.resource ?? '')?.[1];
50
57
  const claim = error?.migrationClaim;
@@ -61,7 +68,7 @@ export function migrationFailure(error, again = 'rer deploy') {
61
68
  const name = safe(unconfirmed.name).replaceAll(' ','?');
62
69
  const run = `npx wrangler d1 execute ${database ?? '<database>'} --remote --command "DELETE FROM d1_migrations WHERE name='${name}' AND sha256='${unconfirmed.sha256}' AND state='applying'"`;
63
70
  return `Migration ${name} in ${database ? `D1 ${database}` : 'its D1 database'} was started on bytes this build does not have (SHA-256 ${unconfirmed.sha256.slice(0,12)}) and never confirmed. ${unconfirmed.rewritten
64
- ? `A reviewed rewrite in migrations/rewrites.json replaces those bytes; rer deploy retries it under its deploy lock, and this run does not hold one.`
71
+ ? `A reviewed rewrite in migrations/rewrites.json replaces those bytes; ~/.local/bin/rer deploy retries it under its deploy lock, and this run does not hold one.`
65
72
  : `No reviewed rewrite in migrations/rewrites.json replaces those bytes, so rer will not run it again.`} D1 imports a migration and its completion marker as one atomic file, so a claim still applying after that attempt ended means none of it applied. Deleting the claim is safe once that attempt has ended (it failed, or its run was stopped) and no other deploy of this environment is running: ${run}, then run ${again} again. While a deploy may still be running, leave it.`;
66
73
  }
67
74
  if (typeof error?.migration === 'string') return `Migration ${safe(error.migration)} did not apply; the next ${again} runs it again once rer proves none of it applied.`;