@runeditrun/rer 0.2.74 → 0.2.76

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 (66) hide show
  1. package/README.md +7 -2
  2. package/cli/export.mjs +1 -1
  3. package/cli/listing.mjs +20 -0
  4. package/cli/main.mjs +1 -0
  5. package/cli/parse.mjs +2 -1
  6. package/cli/portability-migrations.mjs +46 -0
  7. package/cli/portability-worker.mjs +7 -20
  8. package/cli/portability.mjs +5 -4
  9. package/cli/server-registry.mjs +43 -18
  10. package/cli/server-resources.mjs +38 -9
  11. package/cli/site-check.mjs +4 -2
  12. package/cli/site-prepare.mjs +6 -0
  13. package/cli/site-render.mjs +7 -1
  14. package/cli/site-runtime.mjs +55 -0
  15. package/cli/site.mjs +45 -17
  16. package/global/CHANGELOG.md +13 -0
  17. package/global/README.md +7 -2
  18. package/global/launch/state.mjs +5 -4
  19. package/global/launch/stop.mjs +30 -8
  20. package/global/main.mjs +2 -1
  21. package/modules/deploy-kit/README.md +47 -2
  22. package/modules/deploy-kit/owner-cli.mjs +2 -1
  23. package/modules/deploy-kit/site-readback.mjs +12 -2
  24. package/modules/deploy-kit/site-runtime.mjs +33 -0
  25. package/modules/deploy-kit/site.mjs +27 -8
  26. package/modules/job-queue/command.mjs +8 -3
  27. package/modules/portability/README.md +40 -11
  28. package/modules/portability/backfills.mjs +29 -16
  29. package/modules/portability/bridge.mjs +24 -29
  30. package/modules/portability/import.mjs +1 -2
  31. package/modules/portability/index.d.mts +1 -1
  32. package/modules/portability/ledgers.mjs +22 -0
  33. package/modules/portability/migration-history.mjs +2 -2
  34. package/modules/release/README.md +135 -3
  35. package/modules/release/catalogue.mjs +6 -2
  36. package/modules/release/listing.mjs +64 -0
  37. package/modules/release/look.mjs +26 -0
  38. package/modules/release/previous-listing.mjs +44 -0
  39. package/modules/release/produce.mjs +3 -0
  40. package/modules/release/screenshots.mjs +51 -0
  41. package/modules/release/signature.mjs +3 -2
  42. package/modules/release/source.mjs +19 -6
  43. package/modules/release/statement.mjs +8 -4
  44. package/modules/site/docs-search/SearchField.tsx +18 -0
  45. package/modules/site/docs-search/artifacts.mjs +54 -0
  46. package/modules/site/docs-search/client.ts +194 -0
  47. package/modules/site/docs-search/index-build.mjs +63 -0
  48. package/modules/site/docs-search/retrieve.ts +16 -0
  49. package/modules/site/docs-search/search.css +19 -0
  50. package/modules/site/docs-search/sections.ts +24 -0
  51. package/modules/site/docs-search/types.ts +14 -0
  52. package/modules/site/docs-search/worker.ts +39 -0
  53. package/onboarding/process-cleanup.mjs +5 -5
  54. package/onboarding/process-scope.mjs +1 -1
  55. package/onboarding/process-table.mjs +6 -4
  56. package/onboarding/process-tree.mjs +4 -4
  57. package/onboarding/schema/json-schema.mjs +4 -1
  58. package/package.json +1 -1
  59. package/scripts/publish-check/README.md +14 -0
  60. package/scripts/publish-check/assignment.py +48 -0
  61. package/scripts/publish-check/credential_assignments.mjs +75 -0
  62. package/scripts/publish-check/credential_assignments.py +70 -0
  63. package/scripts/publish-check/credential_literals.mjs +66 -0
  64. package/scripts/publish-check/credential_syntax.mjs +29 -0
  65. package/scripts/publish-check/env_values.py +14 -1
  66. package/scripts/publish-check/history_scan.py +9 -2
package/cli/site.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { readFile, rename, rm, mkdir } from 'node:fs/promises';
1
+ import { cp, readFile, rename, rm, mkdir } from 'node:fs/promises';
2
2
  import { dirname, join, relative } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { contained } from './project.mjs';
@@ -9,10 +9,11 @@ import { shared } from './shared.mjs';
9
9
  import { unpublishedIdentities } from './site-private.mjs';
10
10
  import { privateSitePaths } from './site-inputs.mjs';
11
11
  import { redactSiteText } from './site-diagnostics.mjs';
12
+ import { siteRuntime, buildSiteRuntime, runtimeSummary } from './site-runtime.mjs';
12
13
 
13
14
  // The run site: a seed's static marketing pages, /run and docs, built from
14
15
  // edition identity with no installation data. A seed opts in with
15
- // commandAdapter's `site: { entry, output, declaration, config? }`: the module
16
+ // commandAdapter's `site: { entry, output, declaration, config?, runtime? }`: the module
16
17
  // whose sitePages({ styles }) returns the pages, the ignored folder the build
17
18
  // writes, the deploy declaration naming the run site's domain, and optionally
18
19
  // the Vite config holding the plugins the site pages need.
@@ -23,6 +24,8 @@ export function declaredSite(project) {
23
24
  if (!site) throw refuse('This checkout declares no run site. A seed opts in with site: { entry, output, declaration } in its command adapter; see SEED-COMMAND-CONTRACT.md.');
24
25
  if (!relativePath(site.entry) || !relativePath(site.output) || !relativePath(site.declaration) || (site.config !== undefined && !relativePath(site.config)) || (site.clientConfig !== undefined && !relativePath(site.clientConfig)) || ['src', 'public', 'node_modules', 'migrations'].some(top => site.output === top || site.output.startsWith(top + '/'))) throw invalid('The declared run site needs relative entries/configs, an output folder outside src, public and node_modules, and a deploy declaration.');
25
26
  if (site.clients !== undefined && (!site.clients || Array.isArray(site.clients) || typeof site.clients !== 'object' || Object.entries(site.clients).some(([name, entry]) => !/^[a-z][a-z0-9-]*$/i.test(name) || !relativePath(entry)))) throw invalid('Run site clients is a map of island names to relative client entry paths.');
27
+ const runtime = siteRuntime(site.runtime);
28
+ if (runtime && (runtime.corpus.startsWith(site.output + '/') || site.output.startsWith(runtime.corpus + '/'))) throw invalid('Search corpus must be outside the published site assets.');
26
29
  return site;
27
30
  }
28
31
 
@@ -46,19 +49,20 @@ async function privateValues(project) {
46
49
  }
47
50
 
48
51
  /** Render the run site into its declared folder, check it and replace the previous build. */
49
- export async function buildSite(project, store, signal) {
52
+ export async function buildSite(project, store, signal, { prepare = false, deployment } = {}) {
50
53
  const site = declaredSite(project);
51
54
  await contained(project.root, site.entry);
52
55
  if (site.config) await contained(project.root, site.config);
53
56
  if (site.clientConfig) await contained(project.root, site.clientConfig);
54
57
  for (const entry of Object.values(site.clients ?? {})) await contained(project.root, entry);
58
+ if (site.runtime) await contained(project.root, site.runtime.corpus, { optional: true });
55
59
  const folder = await contained(project.root, site.output, { optional: true });
56
60
  await mkdir(dirname(folder), { recursive: true });
57
61
  const staging = `${folder}.building-${process.pid}`;
58
62
  await rm(staging, { recursive: true, force: true });
59
63
  try {
60
64
  await mkdir(staging);
61
- try { await store.run('Building the run site', process.execPath, [fileURLToPath(new URL('./site-render.mjs', import.meta.url)), project.root, site.entry, staging, site.config ?? '', JSON.stringify({entries:site.clients ?? {}, config:site.clientConfig, privatePaths:privateSitePaths(project.adapter)})], { cwd: project.root, signal, heavy: false }); }
65
+ try { await store.run('Building the run site', process.execPath, [fileURLToPath(new URL('./site-render.mjs', import.meta.url)), project.root, site.entry, staging, site.config ?? '', JSON.stringify({entries:site.clients ?? {}, config:site.clientConfig, privatePaths:privateSitePaths(project.adapter), ...(site.runtime ? {runtime:site.runtime, corpus:`${staging}.corpus.json`} : {})})], { cwd: project.root, signal, heavy: false }); }
62
66
  catch (error) {
63
67
  const code = await readFile(`${staging}.refusal`, 'utf8').catch(() => '');
64
68
  if (code === 'site_private_input') throw new RerError(code, 'Run site client imports a private installation file or a file outside the seed and its declared dependencies.', 4);
@@ -69,25 +73,40 @@ export async function buildSite(project, store, signal) {
69
73
  if (diagnostic) throw commandFailure(redactSiteText(diagnostic.message), diagnostic);
70
74
  throw error;
71
75
  }
72
- const checked = await checkSite(staging, {root:project.root, ...await privateValues(project)});
76
+ const privacy = await privateValues(project);
77
+ const checkOptions = {root:project.root, ...privacy, ...(site.runtime ? {runtime:site.runtime} : {})};
78
+ let checked = await checkSite(staging, checkOptions);
79
+ let runtime;
80
+ if (site.runtime) {
81
+ try { runtime = await buildSiteRuntime(project, site.runtime, `${staging}.corpus.json`, staging, { prepare, domain:deployment?.domain, compatibilityDate:deployment?.compatibilityDate, store, signal }); }
82
+ catch (error) { if (error instanceof RerError) throw error; throw new RerError('site_search_failed', 'Docs search preparation failed; publication stopped. Check the previous artifact and Workers AI availability.', 1); }
83
+ if (prepare) checked = await checkSite(staging, checkOptions);
84
+ const corpus = await contained(project.root, site.runtime.corpus, {optional:true});
85
+ await mkdir(dirname(corpus), {recursive:true});
86
+ await cp(`${staging}.corpus.json`, corpus);
87
+ }
73
88
  await rm(folder, { recursive: true, force: true });
74
89
  await rename(staging, folder);
75
- return { folder, ...checked };
76
- } finally { await Promise.all([staging, `${staging}.render`, `${staging}.refusal`].map(path => rm(path, { recursive: true, force: true }))); }
90
+ return { folder, ...checked, ...(runtime ? {runtime} : {}) };
91
+ } finally { await Promise.all([staging, `${staging}.render`, `${staging}.refusal`, `${staging}.corpus.json`].map(path => rm(path, { recursive: true, force: true }))); }
77
92
  }
78
93
 
79
- async function siteDeployment(project, options, folder) {
94
+ async function siteDeployment(project, options, folder, runtime) {
80
95
  const site = declaredSite(project), environment = options.environment ?? 'production';
81
96
  const read = async path => { try { return JSON.parse(await readFile(await contained(project.root, path), 'utf8')); } catch (error) { if (error instanceof RerError) throw error; throw invalid(`Malformed ${path}.`); } };
82
97
  const app = await read(project.adapter.deploy?.declaration ?? 'deploy.json'), declaration = await read(site.declaration);
83
98
  const { sitePlan } = await import('../modules/deploy-kit/site.mjs');
84
- try { return sitePlan({ project: app.project, environment, compatibilityDate: app.compatibilityDate, declaration, assets: folder }); }
99
+ try { return sitePlan({ project: app.project, environment, compatibilityDate: app.compatibilityDate, declaration, assets: folder, runtime }); }
85
100
  catch (error) { throw invalid(`The run site deploy declaration is invalid (${error.message}). ${site.declaration} holds {"version": 1, "domain": "<apex hostname>"}.`); }
86
101
  }
87
102
 
88
103
  /** `rer build --site` and `rer deploy --site [--dry-run]`. */
89
104
  export async function siteCommand(project, options, store, signal, out) {
90
- const built = await buildSite(project, store, signal);
105
+ const prepare = options.verb !== 'build' && !options.dryRun;
106
+ if (prepare && declaredSite(project).runtime && ['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN'].some(name => !process.env[name]?.trim())) throw missing('CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN are required, with the run site token permissions in the deploy-kit README.');
107
+ const declaration = declaredSite(project);
108
+ const deployment = prepare && declaration.runtime ? await siteDeployment(project, options, '/') : undefined;
109
+ const built = await buildSite(project, store, signal, {prepare, deployment});
91
110
  if (!options.json && built.references.unresolved.length) {
92
111
  out.human(`Run site references: ${built.references.unresolved.length} runtime resource target(s) could not be resolved statically:`);
93
112
  for (const {asset, kind} of built.references.unresolved) out.human(` ${asset}: ${kind}`);
@@ -96,13 +115,23 @@ export async function siteCommand(project, options, store, signal, out) {
96
115
  // Output redaction masks an inherited PWD (a credential-shaped name), so the
97
116
  // checkout-relative folder is named too.
98
117
  const path = relative(project.root, built.folder);
99
- if (!options.json) out.human(`Run site written to ${path} (${built.pages} pages, ${built.files} files): ${built.folder}`);
100
- return { site: { folder: built.folder, path, pages: built.pages, files: built.files, references:built.references } };
118
+ if (!options.json) {
119
+ out.human(`Run site written to ${path} (${built.pages} pages, ${built.files} files): ${built.folder}`);
120
+ if (built.runtime) out.human(` runtime: docs-search; endpoint ${built.runtime.endpoint}; bindings ASSETS, AI; corpus ${built.runtime.corpusHash}; vectors prepared only on a real deploy`);
121
+ }
122
+ return { site: { folder: built.folder, path, pages: built.pages, files: built.files, references:built.references, ...(built.runtime ? {runtime:runtimeSummary(built.runtime)} : {}) } };
101
123
  }
102
- const plan = await siteDeployment(project, options, built.folder);
103
- const human = [`Run site plan: site Worker ${plan.worker}, Base-generated, its only binding the assets (the app's Worker ${plan.appWorker} is not touched)`, ` assets: ${plan.assets} (${built.files} files; HTML ${plan.assetsConfig.html_handling}, not found ${plan.assetsConfig.not_found_handling}; the Worker runs first)`,
124
+ const plan = await siteDeployment(project, options, built.folder, built.runtime);
125
+ const human = [`Run site plan: site Worker ${plan.worker}, Base-generated, ${built.runtime ? 'docs-search runtime with ASSETS and AI' : 'its only binding the assets'} (the app's Worker ${plan.appWorker} is not touched)`, ` assets: ${plan.assets} (${built.files} files; HTML ${plan.assetsConfig.html_handling}, not found ${plan.assetsConfig.not_found_handling}; the Worker runs first)`,
104
126
  ` custom domains: ${plan.hostnames.join(', ')}; workers.dev off`, ...plan.redirects.map(rule => ` redirect in the Worker: ${rule.from} -> ${rule.to} (${rule.status}, keeps ${rule.keeps.join(' and ')})`)];
105
- const summary = { worker: plan.worker, appWorker: plan.appWorker, module: plan.module, bindings: plan.bindings, assets: plan.assets, files: built.files, references:built.references, domain: plan.domain, hostnames: plan.hostnames, workersDev: false, runWorkerFirst: true, assetsConfig: plan.assetsConfig, redirects: plan.redirects.map(({ from, to, status }) => ({ from, to, status })) };
127
+ const { collectFiles } = await import('../modules/deploy-kit/artifact.mjs');
128
+ const { siteFingerprint } = await import('../modules/deploy-kit/site.mjs');
129
+ const files = await collectFiles(built.folder);
130
+ const runtime = runtimeSummary(built.runtime);
131
+ if (runtime) human.push(` runtime: ${runtime.type}; module ${runtime.module}; endpoint ${runtime.endpoint}; bindings ${runtime.bindings.join(', ')}; model ${runtime.model}; pooling ${runtime.pooling}; corpus ${runtime.corpusHash}`);
132
+ const fingerprint = siteFingerprint(plan, files, {preparing:Boolean(runtime) && !prepare});
133
+ if (runtime) human.push(` fingerprint: ${fingerprint}${prepare ? '' : ' (vectors prepared only on a real deploy)'}`);
134
+ const summary = { ...(runtime ? {runtime, fingerprint, vectors:prepare ? 'prepared' : 'prepare-on-deploy'} : {}), worker: plan.worker, appWorker: plan.appWorker, module: plan.module, bindings: plan.bindings, assets: plan.assets, files: built.files, references:built.references, domain: plan.domain, hostnames: plan.hostnames, workersDev: false, runWorkerFirst: true, assetsConfig: plan.assetsConfig, redirects: plan.redirects.map(({ from, to, status }) => ({ from, to, status })) };
106
135
  if (options.dryRun) {
107
136
  if (options.json) out.event('site', summary); else for (const line of human) out.human(line);
108
137
  store.report('deploy --site: dry run complete; no deployment occurred and no provider request was made.');
@@ -112,13 +141,12 @@ export async function siteCommand(project, options, store, signal, out) {
112
141
  if (names.some(name => !process.env[name]?.trim())) throw missing('CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN are required, with the run site token permissions in the deploy-kit README.');
113
142
  if (!options.json) for (const line of human) out.human(line);
114
143
  const { cloudflare } = await import('../modules/deploy-kit/provider.mjs');
115
- const { collectFiles } = await import('../modules/deploy-kit/artifact.mjs');
116
144
  const { siteDeploy, siteReadbackSummary } = await import('../modules/deploy-kit/site.mjs');
117
145
  const environment = options.environment ?? 'production';
118
146
  try {
119
147
  const api = cloudflare({ accountId: process.env.CLOUDFLARE_ACCOUNT_ID, token: process.env.CLOUDFLARE_API_TOKEN });
120
148
  // The receipt is for the person; ownership is read from the provider, so a fresh checkout deploys too.
121
- const result = await siteDeploy({ api, plan, files: await collectFiles(built.folder), receiptPath: join(project.root, '.rer', 'deploy', `site-${environment}.json`) });
149
+ const result = await siteDeploy({ api, plan, files, receiptPath: join(project.root, '.rer', 'deploy', `site-${environment}.json`) });
122
150
  return { dryRun: false, deployed: true, origin: result.origin, site: summary };
123
151
  } catch (error) {
124
152
  if (error instanceof RerError) throw error;
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.76
4
+
5
+ - **Patch the maintained TanStack Start security closure (#386).** The default seed and foundation carry the patched Start and server-core dependencies for GHSA-qx66-fv34-fjm8.
6
+ - **Restore across native and Platform migration ledgers (#368, #380, #379).** Match migration files by digest, preserve alias-aware ledger checks, and replay later inserts into carried tables after archived rows are restored.
7
+ - **Carry seed listing metadata through releases (#372).** Listing facts and reusable screenshots follow the release artifact.
8
+ - **Keep runtime custody through exec (#352) and measure actual dev write paths (#383).** Process custody stays within the installation root, and disk admission measures the seed's write paths with the WSL temporary-directory floor.
9
+ - **Correct publication scanning (#371, #387, #389).** Use hosted credential-assignment rules, reject comma-neighbour false assignments, and match environment values only when secret-shaped. Documentation examples use public repository references or explicit logical identifiers.
10
+
11
+ ## 0.2.75
12
+
13
+ - **Custom-origin owner claims use the recorded app origin (#374).** Native deployment inspection retains the configured public origin from the deployment receipt, so owner claim and status work for custom domains while the ownership guard still refuses a claim at a different origin. Existing workers.dev deployments keep their derived origin.
14
+ - **Run sites can opt into build-coupled docs search (#375).** Site builds prepare the search corpus and runtime, deploys reuse published vectors or generate them through Workers AI, and readback verifies the serving runtime with its exact AI/assets bindings. Search results link to document headings and provider failures refuse publication.
15
+
3
16
  ## 0.2.74
4
17
 
5
18
  - **Restores replay more later migrations (#359).** Archive admission and replay accept row-less targets and row-less tables (restored in the destination's definition), RAISE-only guard triggers, statements that read views, and row-preserving CHECK rebuilds, so retained archives from before those migrations restore exactly (Vector: 121 tables / 23 rows; Penny with its settings and clock replayed).
package/global/README.md CHANGED
@@ -190,8 +190,13 @@ or does not report its own (`rer describe` reports `defaults`), so a current
190
190
  checkout never records a limit you did not set.
191
191
  A start is never refused for machine load alone unless `RER_SERVERS_LOAD_THRESHOLD`
192
192
  or `RER_JOBS_LOAD_THRESHOLD` is set; memory and disk guards stay. The disk guard
193
- needs 15 GiB free; `RER_SERVERS_DISK_FLOOR_GIB=N` changes it (CI runners may set
194
- it lower, for example 4; people should not).
193
+ measures installed `node_modules` and `.wrangler` (including local D1 state). It
194
+ requires twice those bytes plus 256 MiB, with a 1 GiB minimum, on the checkout,
195
+ the selected temporary directory (`TMPDIR`, then `TMP`/`TEMP`, then the OS
196
+ default), and the actual `RER_SERVERS_DIR` or home registry directory. A refusal
197
+ names the path and exact free and required bytes.
198
+ `RER_SERVERS_DISK_FLOOR_GIB=N` explicitly replaces this estimate (GiB, decimals
199
+ allowed, 0 disables the floor).
195
200
 
196
201
  ## The front door
197
202
 
@@ -10,7 +10,7 @@
10
10
  // stop.json when rer dev --stop last ran: a launch requested before it stops
11
11
  // pin-install.json the process installing the checkout's pinned rer package
12
12
  import { createHash } from 'node:crypto';
13
- import { appendFile, link, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
13
+ import { appendFile, link, mkdir, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
14
14
  import { basename, join } from 'node:path';
15
15
  import { processInfo } from '../../modules/job-queue/processes.mjs';
16
16
  import { serversDirectory } from '../registry.mjs';
@@ -35,9 +35,10 @@ async function live(holder) {
35
35
  }
36
36
 
37
37
  export async function liveWorker(directory) {
38
- const holder = await readJson(join(directory, 'worker.json'));
38
+ const holder = await readWorker(directory);
39
39
  return await live(holder) ? holder : undefined;
40
40
  }
41
+ export const readWorker = directory => readJson(join(directory, 'worker.json'));
41
42
 
42
43
  // A claim file is written to a private file first and hard-linked into place,
43
44
  // so it appears complete or not at all: a process finding it never reads a
@@ -101,8 +102,8 @@ export async function settledPinInstall(checkout, { env = process.env, signal, o
101
102
  export async function claimLaunch(directory, token) {
102
103
  const path = join(directory, 'worker.json');
103
104
  for (let attempt = 0; attempt < 3; attempt++) {
104
- const { start } = await processInfo(process.pid);
105
- if (await linkClaim(path, { token, pid: process.pid, start, startedAt: Date.now(), events: `events-${token}.jsonl` })) {
105
+ const { start, title: command } = await processInfo(process.pid), checkout = await realpath(process.cwd());
106
+ if (await linkClaim(path, { token, pid: process.pid, start, command, checkout, startedAt: Date.now(), events: `events-${token}.jsonl` })) {
106
107
  for (const entry of await readdir(directory)) if (/^events-.*\.jsonl$/.test(entry) && entry !== `events-${token}.jsonl`) await rm(join(directory, entry), { force: true });
107
108
  return true;
108
109
  }
@@ -5,22 +5,34 @@
5
5
  // the registered server and everything they spawned -- has exited. It says
6
6
  // what it stopped, or exits non-zero naming what is still running.
7
7
  import { setTimeout as delay } from 'node:timers/promises';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { join } from 'node:path';
10
+ import { rm } from 'node:fs/promises';
8
11
  import { processInfo } from '../../modules/job-queue/processes.mjs';
9
12
  import { readProcessTable, sameBirth } from '../../onboarding/process-table.mjs';
10
13
  import { delegate } from '../delegate.mjs';
11
14
  import { liveServers } from '../registry.mjs';
15
+ import { serverStatus } from '../../cli/server-registry.mjs';
12
16
  import { LaunchFailure } from './failure.mjs';
13
- import { liveWorker, serverRecord, stopRequest } from './state.mjs';
17
+ import { readWorker, serverRecord, stopRequest } from './state.mjs';
14
18
 
15
19
  export async function stopLaunch(target, devArgs, { checkout, directory }) {
16
20
  // Written before looking for a worker: one that claims the launch after this
17
21
  // look reads it and ends itself (worker.mjs).
18
22
  await stopRequest.write(directory);
19
- const holder = await liveWorker(directory);
20
- const launch = holder ? await tree([holder]) : [];
21
- if (holder) await endWorker(holder);
23
+ const holder = await readWorker(directory);
24
+ const verified = holder && await verifiedWorker(holder, checkout);
25
+ const launch = verified ? await tree([holder]) : [];
26
+ if (verified) await endWorker(holder, checkout);
27
+ else if (holder) {
28
+ await rm(join(directory, 'worker.json'), { force: true });
29
+ process.stderr.write(`Dropped foreign or unverified launch worker entry for ${checkout}; no signal was sent.\n`);
30
+ }
22
31
  // Only now: a worker stopped while its server came up has registered it.
23
- const record = (await liveServers()).find(item => item.checkout === checkout);
32
+ let record;
33
+ for (const candidate of (await liveServers()).filter(item => item.checkout === checkout)) {
34
+ try { await serverStatus(candidate); record = candidate; break; } catch {}
35
+ }
24
36
  const started = await serverRecord.read(directory);
25
37
  const server = await tree([record?.owner, record?.runtimeProcess, started, started?.spawned]);
26
38
  await delegate(target, ['dev', ...devArgs]);
@@ -28,15 +40,25 @@ export async function stopLaunch(target, devArgs, { checkout, directory }) {
28
40
  const left = await exited([...launch, ...server], 15000);
29
41
  if (left.length) {
30
42
  const pids = left.map(item => item.pid).join(' ');
31
- process.stderr.write(`rer dev --stop: ${left.length === 1 ? 'a process' : `${left.length} processes`} of this checkout's dev server ${left.length === 1 ? 'is' : 'are'} still running 15 seconds after the stop (PID ${pids}). Stop ${left.length === 1 ? 'it' : 'them'} with kill -TERM ${pids}, then run rer dev --stop again.\n`);
43
+ process.stderr.write(`rer dev --stop: ${left.length === 1 ? 'a process' : `${left.length} processes`} recorded for this checkout's dev server ${left.length === 1 ? 'is' : 'are'} still running 15 seconds after the stop (PID ${pids}). Preserve these processes and inspect their ownership before stopping them.\n`);
32
44
  return 1;
33
45
  }
34
- if (!devArgs.includes('--json')) process.stdout.write(said({ checkout, record, started, server, holder, launch }) + '\n');
46
+ if (!devArgs.includes('--json')) process.stdout.write(said({ checkout, record, started, server, holder:verified?holder:undefined, launch }) + '\n');
35
47
  return 0;
36
48
  }
37
49
 
38
50
  // SIGTERM the preparing worker and wait for it to exit.
39
- async function endWorker(holder) {
51
+ async function verifiedWorker(holder, checkout) {
52
+ if (!Number.isSafeInteger(holder.pid) || holder.pid < 2 || typeof holder.token !== 'string') return false;
53
+ const current = await processInfo(holder.pid);
54
+ const worker = fileURLToPath(new URL('./worker.mjs', import.meta.url));
55
+ return Boolean(current && !current.zombie && current.start === holder.start
56
+ && holder.checkout === checkout && current.title === holder.command
57
+ && current.title.includes(`${worker} ${checkout} ${holder.token} `));
58
+ }
59
+
60
+ async function endWorker(holder, checkout) {
61
+ if (!await verifiedWorker(holder, checkout)) return;
40
62
  try { process.kill(holder.pid, 'SIGTERM'); } catch (error) { if (error.code === 'ESRCH') return; throw error; }
41
63
  for (let waited = 0; waited < 60000; waited += 250) {
42
64
  const current = await processInfo(holder.pid);
package/global/main.mjs CHANGED
@@ -45,7 +45,7 @@ pins (installed first by any verb when node_modules holds another), else its ven
45
45
  of a checkout that pins the rer package use it).
46
46
 
47
47
  Checkout verbs: install, setup, dev, demo, preview, build, verify, reset, deploy, signin, export,
48
- import, doctor, describe, check, release. Run rer VERB --help in a checkout for its flags.
48
+ import, doctor, describe, check, release, listing. Run rer VERB --help in a checkout for its flags.
49
49
  `;
50
50
 
51
51
  // The checkout verbs that install the pinned package before they run when
@@ -64,6 +64,7 @@ export async function main(argv) {
64
64
  // verb never inherits it.
65
65
  delete process.env[localDefaults];
66
66
  if (verb === 'update') return (await import('./update/command.mjs')).update(argv.slice(1));
67
+ if (verb === 'listing') return (await import('../cli/listing.mjs')).dispatchListing(argv.slice(1));
67
68
  if (verb === 'business') return (await import('../cli/business/command.mjs')).businessCommand(argv.slice(1));
68
69
  if (verb === 'companion') return (await import('../cli/companion/command.mjs')).companionCommand(argv.slice(1));
69
70
  const notice = await import('./update/notice.mjs');
@@ -181,23 +181,68 @@ A seed's run site (`run-<seed>.com`: its marketing homepage, `/run` and docs, wr
181
181
  The domain is an apex hostname: no scheme, path, port, upper case or `www.`. The plan (`sitePlan`) names:
182
182
 
183
183
  - the Worker `<project>-<environment>--site`. Owner Worker names never contain `--`, so it can never be the installed app's Worker (`<project>-<environment>`), and a site deploy never reads or writes the app Worker or any of its resources;
184
- - its one module, `site-worker.mjs` (`SITE_WORKER`): fixed content Base generates, with no seed code. Its only binding is the assets (`ASSETS`), it runs first on every request (`run_worker_first`), and it has no secrets, no schedules and workers.dev off. A request to `www.<domain>` gets a 301 to `https://<domain>` with path and query kept; every other request is answered from the assets exactly as an assets-only Worker would answer it: the `rer build --site` folder with `html_handling: auto-trailing-slash` (`/run` serves `run.html`) and `not_found_handling: 404-page`;
184
+ - by default its one module, `site-worker.mjs` (`SITE_WORKER`): fixed content Base generates, with no seed code. Its only binding is the assets (`ASSETS`), it runs first on every request (`run_worker_first`), and it has no secrets, no schedules and workers.dev off. A request to `www.<domain>` gets a 301 to `https://<domain>` with path and query kept; every other request is answered from the assets exactly as an assets-only Worker would answer it: the `rer build --site` folder with `html_handling: auto-trailing-slash` (`/run` serves `run.html`) and `not_found_handling: 404-page`;
185
185
  - the apex as a Workers Custom Domain, and `www.<domain>` as a second Custom Domain on the same Worker, so the www host has DNS and a certificate and its requests reach the Worker's redirect.
186
186
 
187
187
  No zone ruleset is read or written. Every request now invokes the Worker: one page view costs one Worker request for the page and one per same-origin file it loads (the default seed's run site: at most 7 per uncached page view).
188
188
 
189
- `rer deploy --site --dry-run` builds the site and prints that plan (`--json`: a `site` event and a result with `dryRun: true`, `deployed: false` and the same `site` object) with no provider request and nothing written, even with `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` set. Without `--dry-run` it needs both inputs. Ownership is read from the provider alone, so a deploy from a fresh checkout (a CI runner with no `.rer/`) recognises the site it deployed before:
189
+ `rer deploy --site --dry-run` builds the site and prints that plan (`--json`: a `site` event and a result with `dryRun: true`, `deployed: false` and the same `site` object) with local build outputs but no provider request or remote write, even with `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` set. Without `--dry-run` it needs both inputs. Ownership is read from the provider alone, so a deploy from a fresh checkout (a CI runner with no `.rer/`) recognises the site it deployed before:
190
190
 
191
191
  - the Worker is the kit's when its latest deployment serves, at 100%, the Worker's newest version, and that version's message annotation is the kit's `rer-site:<fingerprint>` (every site upload sets it);
192
192
  - a Custom Domain is the kit's when its service is the kit's Worker.
193
193
 
194
194
  A read-only preflight reads the zone (it must be in this account, else `site-zone-missing`), the Worker and the zone's Custom Domains, and refuses before any write: `resource-name-collision` for a Worker of the name whose live version the kit did not upload, or for a hostname attached to another service (or to a Worker that is not the kit's); `owned-resource-replaced` for a kit Worker whose latest deployment is not the kit's upload (a dashboard rollback or a split deployment). It then uploads the assets and the site Worker, checks that the new version is live, turns workers.dev off, attaches each missing hostname, and reads the Worker and both domains back. Both post-upload Worker checks share a 90-second upload window: missing visibility or the exact preflight version waits with backoff until the upload response's version serves alone as newest with its expected fingerprint. A foreign version, changed fingerprint or split deployment refuses immediately. A timeout names the last serving/newest versions and fingerprint. A repeat attaches nothing new. `.rer/deploy/site-<environment>.json` receives a receipt for the person; it is never read. Provider propagation cases are tested against the fake Cloudflare API in `tests/site-provider.mjs`, where every zone ruleset path answers 403.
195
195
 
196
+ A seed can opt into docs search through its command adapter's `site.runtime`:
197
+
198
+ ```ts
199
+ runtime: {
200
+ type: 'docs-search', module: 'docs-search', bindings: ['ASSETS', 'AI'],
201
+ endpoint: '/docs/search', corpus: '.rer/docs-search/corpus.json',
202
+ }
203
+ ```
204
+
205
+ This selects Base's docs-search implementation rather than seed JavaScript.
206
+ The site Worker adds the query endpoint and the Workers AI binding; its asset
207
+ handling, www redirect, ownership checks and Custom Domains stay the same.
208
+ No application binding, seed-defined ownership annotation or separate Wrangler
209
+ configuration/deployment is accepted. The domain declaration is unchanged.
210
+ Without `site.runtime`, the assets-only path is unchanged.
211
+
212
+ The renderer produces `pages`, `assets` and
213
+ `searchPages: [{ href, searchSections: [{ anchor, titlePath, text }] }]` from one
214
+ `sitePages` call and writes the latter to the declared staging corpus. Build and
215
+ dry run make no provider or embedding requests. Their plan reports runtime type,
216
+ module, bindings, endpoint, model, pooling, `corpusHash`, module digest and the
217
+ deployment fingerprint; it does not claim vectors exist.
218
+
219
+ Only real deployment prepares vectors. It uses the corpus parent as its local
220
+ preparation/cache directory and always reads the previous published index from
221
+ `https://<site domain>/docs-search-vectors.json`. Model
222
+ `@cf/baai/bge-base-en-v1.5`, pooling `cls` and 768 dimensions are fixed by the
223
+ Base module. Vectors are reused by model, pooling and chunk hash with valid
224
+ matching dimensions. A previous-index 404 permits a first index; other fetch,
225
+ parse or embedding errors stop before any site publication. The same render's
226
+ assets, completed vector index and query module are then uploaded together in
227
+ one site deployment. There is no second render or separate search deployment.
228
+
229
+ The UI source is copied from `modules/site/docs-search` under the seed's chosen
230
+ source path, with `site.clients.docsSearch` naming its `client.ts`. The seed
231
+ renders `SearchField`, imports `search.css`, loads the emitted island module and
232
+ provides `--ink`, `--ink-soft`, `--rule` and `--paper`. The rendered page layout
233
+ and copy stay seed-owned. Local builds have no prepared semantic search service.
234
+
235
+ For CI, the `run-site` environment supplies `CLOUDFLARE_ACCOUNT_ID` from
236
+ `vars.CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` from
237
+ `secrets.CLOUDFLARE_API_TOKEN`. After a frozen install, run the checkout's pinned
238
+ `pnpm exec rer deploy --site`. The guarded template is `export/run-site.yml`.
239
+
196
240
  The token needs, beyond the owner-account permissions above:
197
241
 
198
242
  | Permission | Scope | Used for |
199
243
  | --- | --- | --- |
200
244
  | Workers Scripts: Edit | the account | the site Worker upload, its assets, versions and deployments, workers.dev, and Workers Custom Domains (`/workers/domains`) |
245
+ | Workers AI: Read/Edit | the account, docs-search sites only | preparing embeddings and the runtime AI binding |
201
246
  | Zone: Read | the run site zones | finding the zone by name |
202
247
  | Workers Routes: Edit | the run site zones | Workers Custom Domains, which also create their DNS records and certificates |
203
248
 
@@ -102,7 +102,8 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
102
102
  assert(live && sameDeployment(live, state.receipt.provider), 'owned-resource-replaced');
103
103
  const rows = await api.request(`/workers/scripts/${target.worker}/secrets`);
104
104
  assert(Array.isArray(rows), 'invalid-secret-list');
105
- return {ok:true, origin:target.origin, versionId:live.versionId, retiredSecrets, ownerClaim:state.ownerClaim, liveSecrets:rows.map(row => row.name)};
105
+ // Native uploaders record their configured app origin with the deployment identity.
106
+ return {ok:true, origin:state.receipt.origin ?? target.origin, versionId:live.versionId, retiredSecrets, ownerClaim:state.ownerClaim, liveSecrets:rows.map(row => row.name)};
106
107
  }
107
108
  const current = retiredSecrets.length && Array.isArray(declaration.secrets) ? {...declaration,secrets:declaration.secrets.filter(item => !retiredSecrets.includes(item?.binding))} : declaration;
108
109
  artifact ??= await ownerArtifact(root,values.product);
@@ -1,6 +1,7 @@
1
1
  import { workerSettings } from './owner.mjs';
2
2
  import { readinessAPI } from './readiness-window.mjs';
3
3
  import { assert } from './validation.mjs';
4
+ import { verifySiteRuntime } from './site-runtime.mjs';
4
5
 
5
6
  const ANNOTATION = /^rer-site:[0-9a-f]{64}$/;
6
7
  function refuse(code, worker) { return Object.assign(new Error(code), { resource: `worker:${worker}` }); }
@@ -33,7 +34,7 @@ export async function ownedSiteVersion(api, worker) {
33
34
 
34
35
  /** Only the upload response and the exact preflight version may appear while
35
36
  * Cloudflare's deployment and version reads converge. Never replay the upload. */
36
- export async function waitForSiteUpload({ api, worker, versionId, fingerprint, previous, window }) {
37
+ export async function waitForSiteUpload({ api, worker, versionId, fingerprint, previous, window, runtime, module }) {
37
38
  const bounded = readinessAPI(api, window, 'site-upload-timeout');
38
39
  const annotation = `rer-site:${fingerprint}`;
39
40
  let lastSeen = null, delay = 2000;
@@ -48,7 +49,16 @@ export async function waitForSiteUpload({ api, worker, versionId, fingerprint, p
48
49
  || lastSeen.visible && lastSeen.annotation !== expected
49
50
  || lastSeen.versionId === previous?.versionId && lastSeen.deploymentId !== previous.deploymentId)
50
51
  throw refuse('owned-resource-replaced', worker);
51
- if (lastSeen.current && lastSeen.versionId === versionId && lastSeen.annotation === annotation) return lastSeen;
52
+ if (lastSeen.current && lastSeen.versionId === versionId && lastSeen.annotation === annotation) {
53
+ if (!runtime) return lastSeen;
54
+ try {
55
+ await verifySiteRuntime(bounded, worker, versionId, runtime, module);
56
+ return lastSeen;
57
+ } catch (error) {
58
+ if (window.remaining() <= 0 || error.name === 'TimeoutError') throw timeout(error);
59
+ if (error.status !== 404) throw error;
60
+ }
61
+ }
52
62
  }
53
63
  await window.sleep(Math.min(delay, window.remaining()));
54
64
  delay = Math.min(delay * 2, 10000);
@@ -0,0 +1,33 @@
1
+ import { assert, hash } from './validation.mjs';
2
+
3
+ /** Only the immutable Base docs-search bundle may extend the site Worker. */
4
+ export function siteRuntime(runtime) {
5
+ if (runtime === undefined) return undefined;
6
+ assert(runtime && typeof runtime === 'object' && !Array.isArray(runtime)
7
+ && Object.keys(runtime).sort().join() === 'bindings,corpusHash,endpoint,model,module,pooling,source,type'
8
+ && runtime.type === 'docs-search' && runtime.module === 'docs-search' && runtime.endpoint === '/docs/search'
9
+ && Array.isArray(runtime.bindings) && runtime.bindings.join() === 'ASSETS,AI'
10
+ && typeof runtime.model === 'string' && runtime.model.trim().length > 0 && runtime.pooling === 'cls'
11
+ && typeof runtime.corpusHash === 'string' && /^[a-f0-9]{64}$/.test(runtime.corpusHash)
12
+ && typeof runtime.source === 'string' && runtime.source.length > 0, 'invalid-site-runtime');
13
+ return { ...runtime, bindings: ['ASSETS', 'AI'] };
14
+ }
15
+
16
+ export const siteRuntimeBindings = runtime => [{ type: 'assets', name: 'ASSETS' }, ...(runtime ? [{ type: 'ai', name: 'AI' }] : [])];
17
+
18
+ /** Read the exact version, never Worker-scoped settings or seed annotations.
19
+ * Source equality proves the embedded corpus/model/pooling contract, including
20
+ * its executable implementation, rather than trusting a claimed source digest. */
21
+ export async function verifySiteRuntime(api, worker, versionId, runtime, module) {
22
+ const replaced = () => Object.assign(new Error('owned-resource-replaced'), { resource: `worker:${worker}` });
23
+ const version = await api.request(`/workers/scripts/${worker}/versions/${versionId}`);
24
+ const bindings = version?.resources?.bindings;
25
+ const expected = siteRuntimeBindings(runtime);
26
+ if (version?.id !== versionId || !Array.isArray(bindings) || bindings.length !== expected.length
27
+ || expected.some(binding => bindings.filter(row => row?.name === binding.name && row.type === binding.type).length !== 1)) throw replaced();
28
+ const content = await api.workerContent(worker, versionId);
29
+ const parts = [...content.parts];
30
+ if (content.entry !== module || parts.length !== 1 || parts[0][0] !== module
31
+ || typeof parts[0][1]?.arrayBuffer !== 'function'
32
+ || hash(Buffer.from(await parts[0][1].arrayBuffer())) !== hash(runtime.source)) throw replaced();
33
+ }
@@ -6,11 +6,13 @@ import { uploadAssets, workerOrigin } from './worker.mjs';
6
6
  import { readinessWindow, readinessAPI } from './readiness-window.mjs';
7
7
  import { uploadVersionId } from './uploaded-worker.mjs';
8
8
  import { ownedSiteVersion, waitForSiteDomains, waitForSiteUpload } from './site-readback.mjs';
9
+ import { siteRuntime, siteRuntimeBindings } from './site-runtime.mjs';
9
10
  export { servedVersion, siteReadbackSummary } from './site-readback.mjs';
10
11
 
11
12
  /* A seed's run site (run-<seed>.com): the folder `rer build --site` writes,
12
- * served on the owner's own account by a Base-generated module Worker (fixed
13
- * content, no seed code) whose only binding is its assets. The Worker runs
13
+ * served on the owner's own account by a Base-generated module Worker (no
14
+ * seed code). Its default binding is its assets; opt-in docs search adds AI
15
+ * and an immutable Base-generated search bundle. The Worker runs
14
16
  * first on every request: www.<domain> gets a 301 to the apex with path and
15
17
  * query kept, and everything else is answered from the assets. It has no
16
18
  * secrets and no schedules, workers.dev stays off, and its name can never be
@@ -58,16 +60,32 @@ export function siteWorkerName(project, environment) {
58
60
  }
59
61
 
60
62
  /** Everything a site deploy will do, with no provider request. */
61
- export function sitePlan({ project, environment, compatibilityDate, declaration, assets }) {
63
+ export function sitePlan({ project, environment, compatibilityDate, declaration, assets, runtime }) {
62
64
  const { domain } = siteDeclaration(declaration);
63
65
  assert(/^\d{4}-\d{2}-\d{2}$/.test(compatibilityDate ?? ''), 'invalid-plan');
64
66
  assert(typeof assets === 'string' && assets.startsWith('/'), 'invalid-site-assets');
67
+ runtime = siteRuntime(runtime);
65
68
  return { version: 1, worker: siteWorkerName(project, environment), appWorker: ownerWorkerName(project, environment), module: SITE_MODULE, assets, compatibilityDate,
66
- bindings: ['ASSETS'], secrets: [], crons: [], workersDev: false, runWorkerFirst: true, assetsConfig: { ...SITE_ASSETS_CONFIG },
69
+ bindings: runtime ? [...runtime.bindings] : ['ASSETS'], secrets: [], crons: [], workersDev: false, runWorkerFirst: true, assetsConfig: { ...SITE_ASSETS_CONFIG },
70
+ ...(runtime ? { runtime } : {}),
67
71
  domain, hostnames: [domain, `www.${domain}`],
68
72
  redirects: [{ from: `https://www.${domain}/*`, to: `https://${domain}/`, status: 301, keeps: ['path', 'query'] }] };
69
73
  }
70
74
 
75
+ /** Assets-only plans retain the original fingerprint byte for byte. */
76
+ export function siteFingerprint(plan, files, { preparing = false } = {}) {
77
+ const runtime = siteRuntime(plan.runtime);
78
+ const identity = { files: files.map(({ path, sha256 }) => ({ path, sha256 })), config: plan.assetsConfig,
79
+ module: hash(runtime?.source ?? SITE_WORKER), compatibilityDate: plan.compatibilityDate };
80
+ if (runtime) {
81
+ const vectors = files.find(file => file.path === 'docs-search-vectors.json');
82
+ assert(preparing || vectors && /^[a-f0-9]{64}$/.test(vectors.sha256), 'missing-site-search-vectors');
83
+ identity.runtime = { type: runtime.type, module: runtime.module, endpoint: runtime.endpoint, bindings: runtime.bindings,
84
+ model: runtime.model, pooling: runtime.pooling, corpusHash: runtime.corpusHash, vectors: preparing ? 'prepare-on-deploy' : vectors.sha256 };
85
+ }
86
+ return hash(identity);
87
+ }
88
+
71
89
  async function writeReceipt(path, receipt) {
72
90
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
73
91
  const temporary = `${path}.${process.pid}.tmp`;
@@ -79,6 +97,8 @@ async function writeReceipt(path, receipt) {
79
97
  export async function siteDeploy({ api, plan, files, receiptPath, readiness = {} }) {
80
98
  assert(typeof receiptPath === 'string' && receiptPath.length, 'missing-receipt-path');
81
99
  assert(plan?.module === SITE_MODULE && Array.isArray(files) && files.some(file => file.path === 'index.html'), 'invalid-site-assets');
100
+ const runtime = siteRuntime(plan.runtime);
101
+ const fingerprint = siteFingerprint(plan, files);
82
102
  const zones = await api.zoneRequest(`/zones?name=${plan.domain}&account.id=${api.accountId}`);
83
103
  const zone = Array.isArray(zones) ? zones.find(row => row?.name === plan.domain && row.account?.id === api.accountId) : null;
84
104
  if (!zone) throw refuse('site-zone-missing', 'zone', plan.domain);
@@ -91,19 +111,18 @@ export async function siteDeploy({ api, plan, files, receiptPath, readiness = {}
91
111
  if (row && (!previous || row.service !== plan.worker)) throw refuse('resource-name-collision', 'domain', hostname);
92
112
  }
93
113
 
94
- const fingerprint = hash({ files: files.map(({ path, sha256 }) => ({ path, sha256 })), config: plan.assetsConfig, module: hash(SITE_WORKER), compatibilityDate: plan.compatibilityDate });
95
114
  const jwt = await uploadAssets(api, plan.worker, files);
96
115
  const body = new FormData();
97
- body.set('metadata', new Blob([JSON.stringify({ main_module: SITE_MODULE, compatibility_date: plan.compatibilityDate, bindings: [{ type: 'assets', name: 'ASSETS' }],
116
+ body.set('metadata', new Blob([JSON.stringify({ main_module: SITE_MODULE, compatibility_date: plan.compatibilityDate, bindings: siteRuntimeBindings(runtime),
98
117
  assets: { jwt, config: { ...plan.assetsConfig, run_worker_first: true } }, annotations: { 'workers/message': `rer-site:${fingerprint}` } })], { type: 'application/json' }));
99
- body.set(SITE_MODULE, new Blob([SITE_WORKER], { type: 'application/javascript+module' }), SITE_MODULE);
118
+ body.set(SITE_MODULE, new Blob([runtime?.source ?? SITE_WORKER], { type: 'application/javascript+module' }), SITE_MODULE);
100
119
  const window = readiness.window ?? readinessWindow(readiness);
101
120
  window.start();
102
121
  api = readinessAPI(api, window, 'site-upload-timeout');
103
122
  const upload = await api.request(`/workers/scripts/${plan.worker}`, { method: 'PUT', body });
104
123
  const versionId = uploadVersionId(upload);
105
124
  assert(versionId, 'invalid-upload-version');
106
- const readback = () => waitForSiteUpload({ api, worker: plan.worker, versionId, fingerprint, previous, window });
125
+ const readback = () => waitForSiteUpload({ api, worker: plan.worker, versionId, fingerprint, previous, window, runtime, module: SITE_MODULE });
107
126
  await readback();
108
127
  await workerOrigin(api, plan.worker, { enable: true, workersDev: false });
109
128
  for (const hostname of plan.hostnames) {
@@ -51,13 +51,18 @@ export async function execute(command, job, config, adopt, signal, onStarted, op
51
51
  } finally {
52
52
  signal.removeEventListener('abort', abort);
53
53
  try {
54
- if (owner) await stopGroup(owner, config.killGraceMs);
55
- else child.kill('SIGKILL'); // The supervisor has not been given GO.
54
+ // Stop escaped descendants through custody first, then finish the group
55
+ // this run created even if custody cleanup fails. The ready owner's start
56
+ // time and unique marker protect against a replacement group leader.
57
+ try { await options.cleanup?.(child,outcome); }
58
+ finally {
59
+ if (owner) await stopGroup(owner, config.killGraceMs);
60
+ else child.kill('SIGKILL'); // The supervisor has not been given GO.
61
+ }
56
62
  // Its group is stopped; output still arriving on a dead supervisor's pipes
57
63
  // comes from escaped descendants, which the caller's cleanup stops.
58
64
  if (outcome?.supervisorEnded) { child.stdout?.destroy(); child.stderr?.destroy(); }
59
65
  await exited;
60
- await options.cleanup?.(child,outcome);
61
66
  if (owner?.socket) await unlink(owner.socket).catch(error => { if (error.code !== 'ENOENT') throw error; });
62
67
  } catch (error) { error.keepLease = true; throw error; }
63
68
  }