@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
@@ -1,3 +1,4 @@
1
+ import { pause, combinedSignal, readChunk } from './cancellation.mjs';
1
2
  import { StringDecoder } from 'node:string_decoder';
2
3
  import { assert } from './validation.mjs';
3
4
 
@@ -5,12 +6,12 @@ import { assert } from './validation.mjs';
5
6
  // truncated credential prefix before the caller can redact it.
6
7
  const decodePrefix = bytes => new StringDecoder('utf8').write(bytes.subarray(0,256));
7
8
 
8
- async function bodyPrefix(response) {
9
+ async function bodyPrefix(response, signal) {
9
10
  if (!response.body) return {body:'',complete:true};
10
11
  const reader = response.body.getReader(); let bytes = Buffer.alloc(0), complete = false;
11
12
  try {
12
13
  while (bytes.length < 256) {
13
- const {done,value} = await reader.read();
14
+ const {done,value} = await readChunk(reader,signal);
14
15
  if (done) { complete = true; break; }
15
16
  bytes = Buffer.concat([bytes,value.subarray(0,256-bytes.length)]);
16
17
  }
@@ -21,12 +22,15 @@ async function bodyPrefix(response) {
21
22
 
22
23
  /** One credential-free, bounded request. Retain only bounded response evidence. */
23
24
  /** `expected` holds the deploy identity fields the caller knows; each must match. */
24
- export async function healthRequest({origin, expected, request, timeoutMs, offsetMs, retryIdentityMismatch = false}) {
25
+ export async function healthRequest({origin, expected, request, timeoutMs, offsetMs, retryIdentityMismatch = false, signal}) {
25
26
  const attempt = {offsetMs,status:null,cfRay:null,contentType:null,body:'',errorClass:null};
27
+ signal?.throwIfAborted();
28
+ const requestAbort = combinedSignal(signal,AbortSignal.timeout(timeoutMs));
26
29
  let response;
27
30
  try {
28
- response = await request(`${origin}/health`, {redirect:'manual',signal:AbortSignal.timeout(timeoutMs),headers:{'Cache-Control':'no-cache','Accept':'application/json'}});
31
+ response = await request(`${origin}/health`, {redirect:'manual',signal:requestAbort,headers:{'Cache-Control':'no-cache','Accept':'application/json'}});
29
32
  } catch {
33
+ signal?.throwIfAborted();
30
34
  attempt.errorClass = 'health-transport-failed';
31
35
  return {attempt,transient:true};
32
36
  }
@@ -34,7 +38,8 @@ export async function healthRequest({origin, expected, request, timeoutMs, offse
34
38
  attempt.cfRay = response.headers.get('cf-ray')?.slice(0,256) ?? null;
35
39
  attempt.contentType = response.headers.get('content-type')?.slice(0,256) ?? null;
36
40
  if (response.status !== 200 || response.redirected) {
37
- const prefix = await bodyPrefix(response);
41
+ const prefix = await bodyPrefix(response,requestAbort);
42
+ signal?.throwIfAborted();
38
43
  attempt.body = prefix.body;
39
44
  attempt.errorClass = 'health-http-failed';
40
45
  return {attempt,routePropagation:!response.redirected && response.status === 404 && prefix.complete && prefix.body.trim() === 'error code: 1042',transient:!response.redirected && (response.status === 404 || response.status >= 500 && response.status <= 599)};
@@ -45,7 +50,7 @@ export async function healthRequest({origin, expected, request, timeoutMs, offse
45
50
  const reader = response.body.getReader();
46
51
  try {
47
52
  while (true) {
48
- const {done,value} = await reader.read();
53
+ const {done,value} = await readChunk(reader,requestAbort);
49
54
  if (done) break;
50
55
  bytes = Buffer.concat([bytes, value]);
51
56
  attempt.body = decodePrefix(bytes);
@@ -53,6 +58,7 @@ export async function healthRequest({origin, expected, request, timeoutMs, offse
53
58
  }
54
59
  } finally { await reader.cancel().catch(() => {}); }
55
60
  } catch (error) {
61
+ signal?.throwIfAborted();
56
62
  attempt.errorClass = ['response-too-large','empty-response'].includes(error.message) ? error.message : 'health-transport-failed';
57
63
  // A redirect or permanent status can never become retryable via body IO.
58
64
  return {attempt,transient:attempt.errorClass === 'health-transport-failed' && (response.status === 200 || response.status === 404 || response.status >= 500 && response.status <= 599)};
@@ -79,13 +85,14 @@ const MIN_DELAY_MS = 2000, MAX_DELAY_MS = 10000;
79
85
 
80
86
  /** The total bound includes requests, body reads and backoff; no request starts at the deadline.
81
87
  * Only a transient outcome is retried. Every attempt is recorded, in order, whatever the end. */
82
- export async function waitHealth({origin,receipt,versionId,expected={sourceSha:receipt.source.sha,fingerprint:receipt.fingerprint,versionId},request,timeoutMs=30000,totalMs=90000,clock=()=>performance.now(),sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms)),onAttempt=()=>{},single=false,freshUpload=false,window,retryIdentityMismatch=false}) {
88
+ export async function waitHealth({origin,receipt,versionId,expected={sourceSha:receipt.source.sha,fingerprint:receipt.fingerprint,versionId},request,timeoutMs=30000,totalMs=90000,clock=()=>performance.now(),sleep,signal,onAttempt=()=>{},single=false,freshUpload=false,window,retryIdentityMismatch=false}) {
83
89
  assert(Number.isFinite(totalMs) && totalMs > 0 && totalMs <= 90000 && Number.isFinite(timeoutMs) && timeoutMs > 0,'invalid-health-bound');
84
90
  const start = clock(); const attempts = []; let delay = 1000;
85
91
  while (true) {
92
+ signal?.throwIfAborted();
86
93
  const remaining = Math.min(totalMs - (clock()-start), window?.remaining() ?? Infinity);
87
94
  if (remaining <= 0) break;
88
- const result = await healthRequest({origin,expected,request,timeoutMs:Math.max(1,Math.ceil(Math.min(timeoutMs,remaining))),offsetMs:Math.round(clock()-start),retryIdentityMismatch});
95
+ const result = await healthRequest({origin,expected,request,timeoutMs:Math.max(1,Math.ceil(Math.min(timeoutMs,remaining))),offsetMs:Math.round(clock()-start),retryIdentityMismatch,signal});
89
96
  attempts.push(result.attempt); await onAttempt(result.attempt,attempts);
90
97
  if (!result.attempt.errorClass) return {ok:true,versionId,attempts};
91
98
  // A newly uploaded workers.dev route can briefly disappear even after its
@@ -94,7 +101,7 @@ export async function waitHealth({origin,receipt,versionId,expected={sourceSha:r
94
101
  if (!result.transient || single && result.attempt.errorClass !== 'health-identity-mismatch' && !routePropagation) break;
95
102
  const rest = Math.min(totalMs - (clock()-start), window?.remaining() ?? Infinity);
96
103
  if (rest <= 0) break;
97
- await sleep(Math.min(Math.max(delay,MIN_DELAY_MS),rest)); delay = Math.min(delay*2,MAX_DELAY_MS);
104
+ await pause(Math.min(Math.max(delay,MIN_DELAY_MS),rest),signal,sleep); delay = Math.min(delay*2,MAX_DELAY_MS);
98
105
  }
99
106
  const last = attempts.at(-1);
100
107
  const error = new Error(`${last?.errorClass ?? 'health-timeout'}-last-status-${last?.status ?? 'transport'}`);
@@ -1,3 +1,4 @@
1
+ import { pause, combinedSignal } from './cancellation.mjs';
1
2
  import { servedAsset } from './asset-health.mjs';
2
3
  import { readinessAPI } from './readiness-window.mjs';
3
4
  import { verifyServiceGrants } from './service-grants.mjs';
@@ -23,15 +24,17 @@ export async function waitForDeploymentHealth(url, {
23
24
  headers,
24
25
  fetchImpl = globalThis.fetch,
25
26
  now = Date.now,
26
- sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
27
+ sleep, signal,
27
28
  } = {}) {
28
29
  const deadline = now() + timeoutMs;
29
30
  let lastResult = 'no response';
30
31
  while (now() < deadline) {
32
+ signal?.throwIfAborted();
31
33
  let response;
32
34
  try {
33
- response = await fetchImpl(url, { redirect: 'manual', signal: AbortSignal.timeout(Math.max(1, Math.min(attemptTimeoutMs, deadline - now()))), ...(headers ? { headers } : {}) });
35
+ response = await fetchImpl(url, { redirect: 'manual', signal: combinedSignal(signal,AbortSignal.timeout(Math.max(1, Math.min(attemptTimeoutMs, deadline - now())))), ...(headers ? { headers } : {}) });
34
36
  } catch {
37
+ signal?.throwIfAborted();
35
38
  lastResult = 'network error';
36
39
  }
37
40
  if (response) {
@@ -43,7 +46,7 @@ export async function waitForDeploymentHealth(url, {
43
46
  }
44
47
  }
45
48
  const remaining = deadline - now();
46
- if (remaining > 0) await sleep(Math.min(intervalMs, remaining));
49
+ if (remaining > 0) await pause(Math.min(intervalMs, remaining),signal,sleep);
47
50
  }
48
51
  throw healthError(`Deployment did not become healthy at ${url} within ${timeoutMs}ms; last result: ${lastResult}.`, lastResult === 'network error' ? 'health-transport-failed' : 'health-http-failed', lastResult);
49
52
  }
@@ -52,7 +55,7 @@ export async function waitForDeploymentHealth(url, {
52
55
  * Without `readiness`, /health gets the single bounded window of waitForDeploymentHealth.
53
56
  * With `readiness` (deploy after an upload) it gets the recorded 90-second wait of health-request.mjs.
54
57
  * `asset`, a built file's path, must answer 200 after at most one transient replay. */
55
- export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fetch,timeoutMs=30000,intervalMs=2000,now,sleep,readiness,asset}) {
58
+ export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fetch,timeoutMs=30000,intervalMs=2000,now,sleep,readiness,asset,signal}) {
56
59
  if (readiness?.window) api = readinessAPI(api, readiness.window);
57
60
  assert(receipt?.version === 1 && receipt.accountId === api.accountId && receipt.worker === plan.worker,'receipt-target-mismatch');
58
61
  await verifyServiceGrants(api, plan);
@@ -79,28 +82,28 @@ export async function verifyHealth({api,plan,receipt,fetch:request=globalThis.fe
79
82
  let health;
80
83
  // A Worker without a public route (reached only through service bindings) has no /health to request.
81
84
  if (plan.workersDev === false) health = {ok:true,versionId:current.versionId,route:'none'};
82
- else if (readiness) health = await waitHealth({origin,receipt,versionId:current.versionId,request,timeoutMs,...readiness});
85
+ else if (readiness) health = await waitHealth({origin,receipt,versionId:current.versionId,request,timeoutMs,signal,...readiness});
83
86
  else {
84
87
  // A secret change makes a new version of the same build; until it reaches
85
88
  // every edge, a healthy answer can still name the previous version. Ask again
86
89
  // within the window; any other wrong identity fails at once.
87
- const clock = now ?? Date.now, wait = sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))), start = clock();
90
+ const clock = now ?? Date.now, start = clock();
88
91
  let body;
89
92
  for (;;) {
90
93
  let response;
91
94
  try {
92
- response = await waitForDeploymentHealth(`${origin}/health`,{timeoutMs,intervalMs,attemptTimeoutMs:timeoutMs,headers:{'Cache-Control':'no-cache','Accept':'application/json'},fetchImpl:request,...(now ? {now} : {}),...(sleep ? {sleep} : {})});
93
- } catch (error) { throw new Error(error.code ?? 'health-transport-failed'); }
95
+ response = await waitForDeploymentHealth(`${origin}/health`,{timeoutMs,intervalMs,attemptTimeoutMs:timeoutMs,headers:{'Cache-Control':'no-cache','Accept':'application/json'},fetchImpl:request,signal,...(now ? {now} : {}),...(sleep ? {sleep} : {})});
96
+ } catch (error) { signal?.throwIfAborted(); throw new Error(error.code ?? 'health-transport-failed'); }
94
97
  assert(response.ok && response.status === 200 && !response.redirected,'health-http-failed');
95
- body = await boundedJSON(response,65536);
98
+ body = await boundedJSON(response,65536,signal);
96
99
  const other = body?.ok === true && typeof body.deployment?.versionId === 'string' && body.deployment.versionId !== current.versionId;
97
100
  if (!other || clock() - start + intervalMs > timeoutMs) break;
98
- await wait(intervalMs);
101
+ await pause(intervalMs,signal,sleep);
99
102
  }
100
103
  assert(body?.ok === true && body.deployment?.sourceSha === receipt.source.sha && body.deployment?.fingerprint === receipt.fingerprint && body.deployment?.versionId === current.versionId,'health-identity-mismatch');
101
104
  health = {ok:true,versionId:current.versionId};
102
105
  }
103
- if (asset && origin) health.asset = await servedAsset(origin,asset,request,timeoutMs,readiness ? {window:readiness.window,windowMs:60000,...(readiness.clock ? {clock:readiness.clock} : {}),...(readiness.sleep ? {sleep:readiness.sleep} : {})} : {});
106
+ if (asset && origin) health.asset = await servedAsset(origin,asset,request,timeoutMs,readiness ? {signal,window:readiness.window,windowMs:60000,...(readiness.clock ? {clock:readiness.clock} : {}),...(readiness.sleep ? {sleep:readiness.sleep} : {})} : {signal});
104
107
  const after = await activeWorker(api,plan.worker);
105
108
  assert(after.versionId === current.versionId && after.deploymentId === current.deploymentId && after.etag === current.etag,'deployment-changed-during-health');
106
109
  await verifyServiceGrants(api, plan);
@@ -1,6 +1,8 @@
1
1
  import { readinessWindow, rememberReadiness } from './readiness-window.mjs';
2
2
  import { deploymentDiagnostics, deployDiagnostic } from './diagnostics.mjs';
3
- import { execFileSync } from 'node:child_process';
3
+ import { execFile } from 'node:child_process';
4
+ import { promisify } from 'node:util';
5
+ import { combinedSignal } from './cancellation.mjs';
4
6
  import { resolve, join } from 'node:path';
5
7
  import { pathToFileURL } from 'node:url';
6
8
  import { parseArgs } from 'node:util';
@@ -9,7 +11,7 @@ import { assert, hexId } from './validation.mjs';
9
11
  import { regularBytes } from './artifact.mjs';
10
12
  import { packageBuild } from './prepare.mjs';
11
13
  import { cloudflare } from './provider.mjs';
12
- import { ownerTarget, recordedOwnerTarget, ownerWorkerName, ownerPlan, ownerDeploy, ownerHealth, settleOwnerState, sameDeployment, localOnlyBinding, withStateLock, readOwnerState, writeOwnerState, workerSettings, withScopeHints } from './owner.mjs';
14
+ import { ownerTarget, ownerStateTarget, recordedOwnerTarget, ownerWorkerName, ownerPlan, ownerDeploy, ownerHealth, settleOwnerState, sameDeployment, localOnlyBinding, withStateLock, readOwnerState, writeOwnerState, workerSettings, withScopeHints } from './owner.mjs';
13
15
  import { activeWorker, secretBindings } from './worker.mjs';
14
16
  import { ownerSecret } from './owner-secret.mjs';
15
17
  import { ownerRemove } from './owner-remove.mjs';
@@ -26,18 +28,41 @@ const usage = 'usage: owner-cli.mjs deploy|dry-run|local-plan|health|remove|insp
26
28
  // The public offline command also contains legacy hooks that call kit dry-run.
27
29
  // Keep their plan local without changing direct kit callers or real deploys.
28
30
  const localPlans = new AsyncLocalStorage();
31
+ const ownerSignals = new AsyncLocalStorage();
32
+ export const withOwnerDeploySignal = (signal, run) => ownerSignals.run(signal, run);
33
+ const execute = promisify(execFile);
29
34
  export const withLocalDeployPlan = run => localPlans.run(true, run);
30
35
 
31
36
  /** The owner's committed source and existing local build. Run the seed's build first. */
32
- async function ownerArtifact(root, product) {
33
- const git = (...args) => { try { return execFileSync('git',args,{cwd:root,encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim(); } catch { throw new Error('owner-source-not-a-git-checkout'); } };
34
- const source = {sha:git('rev-parse','HEAD'),tree:git('rev-parse','HEAD^{tree}')};
35
- assert(!git('status','--porcelain','--untracked-files=no'),'owner-source-not-committed');
37
+ async function ownerArtifact(root, product, signal) {
38
+ const git = async (...args) => {
39
+ signal?.throwIfAborted();
40
+ const grouped = process.platform !== 'win32';
41
+ const pending = execute('git',args,{cwd:root,encoding:'utf8',stdio:['ignore','pipe','pipe'],detached:grouped});
42
+ // Git may invoke a configured helper. End this invocation's entire process
43
+ // group, and await execFile's close callback before returning cancellation.
44
+ const abort = () => {
45
+ if (!pending.child.pid) return;
46
+ try { process.kill(grouped ? -pending.child.pid : pending.child.pid,'SIGKILL'); }
47
+ catch (error) { if (error.code !== 'ESRCH') pending.child.kill('SIGKILL'); }
48
+ };
49
+ signal?.addEventListener('abort',abort,{once:true});
50
+ if (signal?.aborted) abort();
51
+ try { const result = await pending; signal?.throwIfAborted(); return result.stdout.trim(); }
52
+ catch { signal?.throwIfAborted(); throw new Error('owner-source-not-a-git-checkout'); }
53
+ finally { signal?.removeEventListener('abort',abort); }
54
+ };
55
+ const source = {sha:await git('rev-parse','HEAD'),tree:await git('rev-parse','HEAD^{tree}')};
56
+ assert(!await git('status','--porcelain','--untracked-files=no'),'owner-source-not-committed');
57
+ signal?.throwIfAborted();
36
58
  return packageBuild({root,source,runIdentity:{id:'0',attempt:'1'},productDirectory:product});
37
59
  }
38
60
 
39
61
  /** Inputs: CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN, plus the secrets the declaration names on first deploy. */
40
- export async function main(argv = process.argv.slice(2), env = process.env, {fetch = globalThis.fetch, cwd = process.cwd(), healthOptions, propagation, settle, localOnlyKeys = [], notice = line => console.error(line), onCreated} = {}) {
62
+ export async function main(argv = process.argv.slice(2), env = process.env, {fetch = globalThis.fetch, cwd = process.cwd(), healthOptions, propagation, settle, signal = ownerSignals.getStore(), localOnlyKeys = [], notice = line => console.error(line), onCreated} = {}) {
63
+ signal?.throwIfAborted();
64
+ healthOptions = {...healthOptions,signal,...(healthOptions?.readiness ? {readiness:{...healthOptions.readiness,signal}} : {})};
65
+ settle = {...settle,signal};
41
66
  let parsed;
42
67
  try { parsed = parseArgs({args:argv,allowPositionals:true,strict:true,options:{declaration:{type:'string'},environment:{type:'string'},product:{type:'string',default:''},state:{type:'string'},set:{type:'string',multiple:true},unset:{type:'string',multiple:true},outcome:{type:'string'}}}); }
43
68
  catch { throw new Error('usage'); }
@@ -82,32 +107,35 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
82
107
  let requestWindow = propagation?.uploaded ? propagation.window : undefined;
83
108
  const request = fetch;
84
109
  const guardedRequest = (input, init = {}) => {
110
+ signal?.throwIfAborted();
85
111
  init.signal?.throwIfAborted();
86
112
  // The window clock can expire before its shared abort timer fires.
87
113
  assert(!requestWindow?.active || requestWindow.remaining() > 0, 'deployment-readiness-timeout');
88
114
  return request(input, init);
89
115
  };
90
116
  const requestSignal = () => {
91
- if (!requestWindow?.active) return undefined;
117
+ signal?.throwIfAborted();
118
+ if (!requestWindow?.active) return signal;
92
119
  const remaining = requestWindow.remaining();
93
120
  assert(remaining > 0, 'deployment-readiness-timeout');
94
- return requestWindow.timeout(Math.max(1, Math.ceil(remaining)));
121
+ return combinedSignal(signal, requestWindow.timeout(Math.max(1, Math.ceil(remaining))));
95
122
  };
96
123
  fetch = (input, init = {}) => {
97
- const deadline = requestSignal();
98
- return request(input, {...init,...(deadline ? {signal:init.signal ? AbortSignal.any([init.signal,deadline]) : deadline} : {})});
124
+ const requestAbort = combinedSignal(init.signal, requestSignal());
125
+ requestAbort?.throwIfAborted();
126
+ return request(input, {...init,signal:requestAbort});
99
127
  };
100
128
  // Transport must see the same outer signal when deciding whether to retry.
101
129
  const api = deploymentDiagnostics(cloudflare({accountId:env.CLOUDFLARE_ACCOUNT_ID,token:env.CLOUDFLARE_API_TOKEN,fetch:guardedRequest,requestSignal,budgetMigrations:command === 'deploy',...(command === 'remove' ? {maxRequests:Infinity,removal:true} : {})}),{onCreated});
102
130
  const statePath = values.state ? resolve(root,values.state) : join(root,'.rer','deploy',`${values.environment}.json`);
103
- // Signin uses only the selected app record; never discover a sibling page Worker.
104
- // Removal needs the recorded account/name identity, not a workers.dev route.
131
+ // Every follow-up uses the app record's resolved name, including native
132
+ // uploaders' prefixes. Removal needs no routable origin or completed receipt.
105
133
  const target = command === 'signin'
106
134
  ? await recordedOwnerTarget(api,{project:declaration.project,environment:values.environment,statePath})
107
135
  : command === 'remove'
108
- ? {accountId:api.accountId,project:declaration.project,environment:values.environment,worker:ownerWorkerName(declaration.project,values.environment)}
109
- : await ownerTarget(api,{project:declaration.project,environment:values.environment});
110
- if (command === 'remove') return {ok:true,...await ownerRemove({api,target,statePath}).catch(error => { throw api.annotateFailure(error,'remove'); })};
136
+ ? await ownerStateTarget(api,{project:declaration.project,environment:values.environment,statePath})
137
+ : await ownerTarget(api,{project:declaration.project,environment:values.environment,statePath});
138
+ if (command === 'remove') return {ok:true,...await ownerRemove({api,target,statePath,signal}).catch(error => { throw api.annotateFailure(error,'remove'); })};
111
139
  if (command === 'rekey') return ownerRekey({api,target,statePath,declaration,env,notice});
112
140
  if (command === 'secret') {
113
141
  // Every named secret is changed in one Worker version, or none is.
@@ -115,7 +143,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
115
143
  const undeclared = named.filter(binding => !declared.some(entry => entry?.binding === binding));
116
144
  if (undeclared.length) { const error = new Error('undeclared-secret'); error.resource = undeclared.map(binding => `secret:${binding}`).join(', '); throw error; }
117
145
  const changes = named.map(binding => ({binding, value:values.set === undefined ? undefined : env[declared.find(entry => entry?.binding === binding).environment], ...(values.unset !== undefined && Object.hasOwn(publicDefaults,binding) ? {publicDefault:publicDefaults[binding]} : {})}));
118
- return {ok:true,...await ownerSecret({api,target,statePath,changes,fetch,healthOptions,settle}).catch(error => { throw api.annotateFailure(error,'secrets'); })};
146
+ return {ok:true,...await ownerSecret({api,target,statePath,changes,fetch,healthOptions,settle,signal}).catch(error => { throw api.annotateFailure(error,'secrets'); })};
119
147
  }
120
148
  // A secret rer retired (the spent setup token) is no longer part of the plan.
121
149
  // A dry run only reads state: settling an interrupted change may write it.
@@ -146,7 +174,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
146
174
  return {ok:true, origin:state.receipt.origin ?? target.origin, versionId:live.versionId, retiredSecrets, ownerClaim:state.ownerClaim, liveSecrets:rows.map(row => row.name)};
147
175
  }
148
176
  const current = retiredSecrets.length && Array.isArray(declaration.secrets) ? {...declaration,secrets:declaration.secrets.filter(item => !retiredSecrets.includes(item?.binding))} : declaration;
149
- artifact ??= await ownerArtifact(root,values.product);
177
+ artifact ??= await ownerArtifact(root,values.product,signal);
150
178
  const plan = ownerPlan(target,current,artifact,{localOnlyKeys,env,publicDefaults});
151
179
  if (command === 'dry-run') {
152
180
  const checked = withScopeHints(api);
@@ -156,7 +184,7 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
156
184
  }
157
185
  if (command === 'health') {
158
186
  const readiness = {...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}),
159
- ...healthOptions?.readiness,single:true,totalMs:30000,
187
+ ...healthOptions?.readiness,signal,single:true,totalMs:30000,
160
188
  ...(propagation ? {window:propagation.window,freshUpload:propagation.uploaded && propagation.versionId === state.receipt?.provider.versionId} : {})};
161
189
  await ownerHealth({api,target,plan,statePath,fetch,healthOptions:{...healthOptions,readiness}}).catch(error=>{throw api.annotateFailure(error,'health');});
162
190
  return {ok:true,worker:target.worker,origin:target.origin};
@@ -165,9 +193,9 @@ export async function main(argv = process.argv.slice(2), env = process.env, {fet
165
193
  if (plan.crons.length) notice(cronNotice);
166
194
  // The fingerprint names every declared secret, retired ones too: an untouched repeat after the claim is a no-op.
167
195
  const declaredSecrets = current === declaration ? plan.secrets : ownerPlan(target,declaration,artifact,{localOnlyKeys,env,publicDefaults}).secrets;
168
- const window = readinessWindow({...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}), ...healthOptions?.readiness});
196
+ const window = readinessWindow({...(healthOptions?.now ? {clock:healthOptions.now} : {}), ...(healthOptions?.sleep ? {sleep:healthOptions.sleep} : {}), ...healthOptions?.readiness,signal});
169
197
  requestWindow = window;
170
- const {receipt,created,sentSecrets,unsetSecrets,freshUpload} = await ownerDeploy({api,target,plan,artifact,statePath,env,fetch,healthOptions,readiness:{...healthOptions?.readiness,window},settle,declaredSecrets}).catch(error => {
198
+ const {receipt,created,sentSecrets,unsetSecrets,freshUpload} = await ownerDeploy({api,target,plan,artifact,statePath,env,fetch,healthOptions,readiness:{...healthOptions?.readiness,window,signal},settle,declaredSecrets}).catch(error => {
171
199
  api.annotateFailure(error,error.message.startsWith('missing-secret-') ? 'secrets' : undefined);
172
200
  throw error;
173
201
  });
@@ -1,3 +1,4 @@
1
+ import { pause } from './cancellation.mjs';
1
2
  import { r2ObjectPages, r2ObjectPath } from './r2-objects.mjs';
2
3
  import { rm } from 'node:fs/promises';
3
4
  import { assert, hexId } from './validation.mjs';
@@ -38,8 +39,8 @@ async function confirmEmpty(api, worker, kind, name, id) {
38
39
  * everything before the first delete; a replaced or uncertain resource refuses it all,
39
40
  * except an uncertain one confirmed empty (see confirmEmpty). R2 object purges
40
41
  * additionally require the saved creation timestamp and recheck it before each delete. */
41
- export async function ownerRemove({api: provider, target, statePath, clock, sleep}) {
42
- const api = withSettledLists(withScopeHints(provider));
42
+ export async function ownerRemove({api: provider, target, statePath, clock, sleep, signal}) {
43
+ const api = withSettledLists(withScopeHints(provider),{signal});
43
44
  return withStateLock(statePath, async () => {
44
45
  const state = await readOwnerState(statePath, target);
45
46
  const remaining = new Set([...(state.owned.worker ? [`worker:${target.worker}`] : []), ...KINDS.flatMap(kind => Object.keys(state.owned[kind]).map(name => `${kind}:${name}`))]);
@@ -80,13 +81,13 @@ export async function ownerRemove({api: provider, target, statePath, clock, slee
80
81
  await api.request(`/queues/${queue.id}/consumers/${consumer.consumer_id}`, {method:'DELETE'});
81
82
  }
82
83
  }
83
- if (worker) { await deleteWorker({api, worker, ...(clock ? {clock} : {}), ...(sleep ? {sleep} : {})}); removed.push(`worker:${worker}`); }
84
+ if (worker) { await deleteWorker({api, worker, signal, ...(clock ? {clock} : {}), ...(sleep ? {sleep} : {})}); removed.push(`worker:${worker}`); }
84
85
  for (const item of doomed) {
85
86
  try {
86
87
  if (item.kind === 'r2') await removeBucket(api, item);
87
88
  else {
88
89
  await remove[item.kind](api, item.id, item.name);
89
- if (item.kind === 'queues') await waitForQueueRemoval(api,item,{clock,sleep});
90
+ if (item.kind === 'queues') await waitForQueueRemoval(api,item,{clock,sleep,signal});
90
91
  }
91
92
  removed.push(`${item.kind}:${item.name}`);
92
93
  }
@@ -165,7 +166,7 @@ async function removeBucket(api, {name, entry}) {
165
166
 
166
167
  // Queue deletion and its account listing can settle separately. Finish the
167
168
  // readback within this removal invocation, without replaying the DELETE.
168
- async function waitForQueueRemoval(api, item, {clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve,ms))}) {
169
+ async function waitForQueueRemoval(api, item, {clock = () => performance.now(), sleep, signal}) {
169
170
  const start = clock();
170
171
  for (;;) {
171
172
  if (!(await resourceKinds.queues.list(api)).some(row => row.queue_id === item.id)) return;
@@ -174,6 +175,6 @@ async function waitForQueueRemoval(api, item, {clock = () => performance.now(),
174
175
  error.providerCall = {operation:'GET /queues',reason:'Cloudflare still lists the deleted queue after 60 seconds'};
175
176
  throw error;
176
177
  }
177
- await sleep(500);
178
+ await pause(500,signal,sleep);
178
179
  }
179
180
  }
@@ -1,3 +1,4 @@
1
+ import { pause } from './cancellation.mjs';
1
2
  import { randomBytes } from 'node:crypto';
2
3
  import { assert, identifier } from './validation.mjs';
3
4
  import { activeWorker } from './worker.mjs';
@@ -20,8 +21,8 @@ import { uploadSecretCopy, deploySecretCopy } from './owner-secret-copy.mjs';
20
21
  * deployment is still live. An ambiguous one-secret rotation
21
22
  * re-PUTs the value before accepting its successor as proof of the rotation.
22
23
  * A removed declared secret is retired: later plans omit it until it is set again. */
23
- export async function ownerSecret({api: provider, target, statePath, changes, fetch = globalThis.fetch, healthOptions = {}, settle = {}, windowMs = 30000, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))}) {
24
- const api = withSettledLists(withScopeHints(provider),settle);
24
+ export async function ownerSecret({api: provider, target, statePath, changes, fetch = globalThis.fetch, healthOptions = {}, settle = {}, windowMs = 30000, clock = () => performance.now(), sleep, signal}) {
25
+ const api = withSettledLists(withScopeHints(provider),{...settle,signal});
25
26
  const bindings = changes.map(change => change.binding), present = changes[0]?.value !== undefined;
26
27
  assert(bindings.length && bindings.every(identifier) && validSecretNames(bindings), 'invalid-secret-name');
27
28
  assert(changes.every(change => (change.value !== undefined) === present), 'mixed-secret-change');
@@ -59,11 +60,12 @@ export async function ownerSecret({api: provider, target, statePath, changes, fe
59
60
  // pending: the same command deploys it next time, as this change and no other.
60
61
  if (definiteProviderRefusal(error) && !uploaded) { delete state.pendingSecret; await writeOwnerState(statePath, state); throw error; }
61
62
  if (definiteProviderRefusal(error)) { await writeOwnerState(statePath, state); throw error; }
63
+ signal?.throwIfAborted();
62
64
  failure = error;
63
65
  }
64
66
  try {
65
67
  if (!changed) recordSecretChange(state, live, state.pendingSecret);
66
- else for (const start = clock(); ; await sleep(2000)) {
68
+ else for (const start = clock(); ; await pause(2000,signal,sleep)) {
67
69
  try {
68
70
  if (await settlePendingSecret(api, target.worker, state, {
69
71
  observe: current => { unchanged = sameDeployment(current, state.receipt.provider); },
@@ -79,6 +81,7 @@ export async function ownerSecret({api: provider, target, statePath, changes, fe
79
81
  })) break;
80
82
  }
81
83
  catch (error) {
84
+ signal?.throwIfAborted();
82
85
  unchanged = false;
83
86
  // Another ambiguous PUT cannot prove a rotation by presence either.
84
87
  // Keep both starting versions for recovery; do not report it done.
@@ -101,7 +104,7 @@ export async function ownerSecret({api: provider, target, statePath, changes, fe
101
104
  if (state.receipt.origin) await waitHealth({
102
105
  origin:state.receipt.origin, receipt:state.receipt, versionId:result.versionId, request:fetch,
103
106
  timeoutMs:healthOptions.timeoutMs,
104
- clock:healthOptions.now, sleep:healthOptions.sleep, ...healthOptions.readiness,
107
+ clock:healthOptions.now, sleep:healthOptions.sleep, signal, ...healthOptions.readiness,
105
108
  });
106
109
  const after = await activeWorker(api, target.worker);
107
110
  assert(after && sameDeployment(after, state.receipt.provider), 'deployment-changed-during-health');
@@ -1,7 +1,9 @@
1
+ import { pause } from './cancellation.mjs';
2
+ import { shared } from '../../cli/shared.mjs';
1
3
  import { readinessWindow } from './readiness-window.mjs';
2
4
  import { uploadedWorker } from './uploaded-worker.mjs';
3
5
  import { ingressBindings } from './container-config.mjs';
4
- import { mkdir, open, rename, rm, writeFile } from 'node:fs/promises';
6
+ import { mkdir, rename, writeFile } from 'node:fs/promises';
5
7
  import { dirname } from 'node:path';
6
8
  import { assert, hash, identifier, resourceName, uuid, validatePlan } from './validation.mjs';
7
9
  import { definiteProviderRefusal } from './provider.mjs';
@@ -71,15 +73,16 @@ export const LIST_WINDOW_MS = 120000;
71
73
  const settleable = error => ['provider-partial-list','provider-pagination-changed'].includes(error.message);
72
74
  /** Owner mode replays a list read, and a GET of a path the provider reads as a list (a Worker's
73
75
  * deployments or versions), until a complete snapshot arrives or the window closes. */
74
- export function withSettledLists(api, {windowMs = LIST_WINDOW_MS, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))} = {}) {
76
+ export function withSettledLists(api, {windowMs = LIST_WINDOW_MS, clock = () => performance.now(), sleep, signal} = {}) {
75
77
  if (api.settledLists) return api;
76
78
  const settled = read => async (...args) => {
77
79
  const start = clock();
78
80
  for (let delay = 500; ; delay = Math.min(delay * 2, 4000)) {
81
+ signal?.throwIfAborted();
79
82
  try { return await read(...args); }
80
83
  catch (error) {
81
84
  if (!settleable(error) || clock() - start + delay > windowMs) throw error;
82
- await sleep(delay);
85
+ await pause(delay,signal,sleep);
83
86
  }
84
87
  }
85
88
  };
@@ -90,13 +93,14 @@ export function withSettledLists(api, {windowMs = LIST_WINDOW_MS, clock = () =>
90
93
  }
91
94
  /** Waits until the account's listing shows a resource this run just created, so no later
92
95
  * read mistakes it for a missing or replaced one. One that never appears is named. */
93
- async function listedAfterCreate(api, kind, item, {windowMs = LIST_WINDOW_MS, clock = () => performance.now(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms))} = {}) {
96
+ async function listedAfterCreate(api, kind, item, {windowMs = LIST_WINDOW_MS, clock = () => performance.now(), sleep, signal} = {}) {
94
97
  const start = clock();
95
98
  for (let delay = 500; ; delay = Math.min(delay * 2, 4000)) {
99
+ signal?.throwIfAborted();
96
100
  try { if (findResource(await resourceKinds[kind].list(api.unsettled ?? api),kind,item.name)) return; }
97
101
  catch (error) { if (!settleable(error)) throw error; }
98
102
  if (clock() - start + delay > windowMs) throw refuse('resource-not-listed',kind,item.name);
99
- await sleep(delay);
103
+ await pause(delay,signal,sleep);
100
104
  }
101
105
  }
102
106
  /** Reads the account's workers.dev subdomain; no other provider request. */
@@ -109,21 +113,36 @@ async function workerOrigin(provider, worker) {
109
113
  assert(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(result.subdomain),'invalid-account-subdomain');
110
114
  return `https://${worker}.${result.subdomain}.workers.dev`;
111
115
  }
112
- export async function ownerTarget(api, {project, environment}) {
113
- const worker = ownerWorkerName(project, environment);
114
- return {accountId:api.accountId,project,environment,worker,origin:await workerOrigin(api,worker)};
116
+ export async function ownerTarget(api, {project, environment, statePath}) {
117
+ const target = await ownerStateTarget(api,{project,environment,statePath});
118
+ return {...target,origin:target.origin ?? await workerOrigin(api,target.worker)};
115
119
  }
116
120
 
117
- /** Signin follows the selected app record, including native uploaders' custom names.
118
- * The caller still supplies the account, project and environment to validate it.
119
- * Later state reads and the live provider check must corroborate this identity. */
120
- export async function recordedOwnerTarget(api, {project, environment, statePath}) {
121
- ownerWorkerName(project, environment); // Validate the caller's project and environment as usual.
121
+ /** Native uploaders record their resolved Worker name. Follow it only within the
122
+ * caller's account, project and environment. An absent record keeps the original
123
+ * derived name; partial records remain usable for recovery and removal. */
124
+ export async function ownerStateTarget(api, {project, environment, statePath}) {
125
+ const worker = ownerWorkerName(project, environment);
126
+ const target = {accountId:api.accountId,project,environment,worker};
127
+ if (statePath === undefined) return target;
122
128
  let recorded;
123
129
  try { recorded = JSON.parse(await regularBytes(statePath, 4 * 1024 * 1024)); }
124
- catch (error) { throw new Error(error.code === 'ENOENT' ? 'missing-owner-receipt' : 'invalid-owner-state'); }
130
+ catch (error) { if (error.code === 'ENOENT') return target; throw new Error('invalid-owner-state'); }
125
131
  assert(resourceName(recorded?.worker), 'invalid-owner-state');
126
- const target = {accountId:api.accountId,project,environment,worker:recorded.worker};
132
+ const selected = {...target,worker:recorded.worker};
133
+ let state;
134
+ try { state = await readOwnerState(statePath,selected); }
135
+ catch (error) {
136
+ if (error.message === 'owner-state-target-mismatch') error.ownerTargetMismatch.requestedWorker = worker;
137
+ throw error;
138
+ }
139
+ return {...selected,...(state.receipt?.origin ? {origin:state.receipt.origin} : {})};
140
+ }
141
+
142
+ /** Signin requires a completed record and never discovers a sibling Worker. */
143
+ export async function recordedOwnerTarget(api, options) {
144
+ const target = await ownerStateTarget(api,options);
145
+ const {statePath} = options;
127
146
  const state = await readOwnerState(statePath,target);
128
147
  assert(state.receipt, 'missing-owner-receipt');
129
148
  return {...target,origin:state.receipt.origin ?? await workerOrigin(api,target.worker)};
@@ -218,7 +237,11 @@ export async function readOwnerState(path, target) {
218
237
  && (pending.names === undefined || validSecretNames(pending.names) && !pending.names.some(name => pending.bindings.includes(name))), 'invalid-owner-state');
219
238
  assert(state.ownerClaim === undefined || ['claimed','kept'].includes(state.ownerClaim?.outcome), 'invalid-owner-state');
220
239
  assert(state.retiredSecrets === undefined || Array.isArray(state.retiredSecrets) && state.retiredSecrets.every(identifier), 'invalid-owner-state');
221
- assert(state.accountId === target.accountId && state.project === target.project && state.environment === target.environment && state.worker === target.worker, 'owner-state-target-mismatch');
240
+ if (state.accountId !== target.accountId || state.project !== target.project || state.environment !== target.environment || state.worker !== target.worker) {
241
+ const error = new Error('owner-state-target-mismatch');
242
+ error.ownerTargetMismatch = {recordedWorker:state.worker,requestedWorker:target.worker};
243
+ throw error;
244
+ }
222
245
  return state;
223
246
  }
224
247
  export async function writeOwnerState(path, state) {
@@ -373,18 +396,13 @@ async function checkOwnedWorker(api, plan, state, save) {
373
396
  return checkWorkerIdentity(api, plan, state, save);
374
397
  }
375
398
 
376
- /** One deploy at a time per state file: an exclusive lock file for the whole run. */
399
+ /** One deploy per state file. A killed writer's lock is reclaimed only after
400
+ * its PID/start identity is dead, using the local operation's exclusive takeover. */
377
401
  export async function withStateLock(path, run) {
378
402
  await mkdir(dirname(path),{recursive:true,mode:0o700});
379
- const lock = `${path}.lock`;
380
- let handle;
381
- try { handle = await open(lock,'wx',0o600); }
382
- catch (error) { throw error.code === 'EEXIST' ? new Error('owner-state-locked') : error; }
383
- try {
384
- await handle.writeFile(`${process.pid}\n`);
385
- await handle.close();
386
- return await run();
387
- } finally { try { await handle.close(); } finally { await rm(lock,{force:true}); } }
403
+ const { fileOperation } = await shared('local/operation.mjs');
404
+ const lock = await fileOperation(`${path}.lock`, undefined, () => new Error('owner-state-locked'));
405
+ try { return await run(); } finally { await lock.release(); }
388
406
  }
389
407
 
390
408
  /** Find or create every declared resource under the owner's account, migrate, upload and check health.
@@ -446,7 +464,7 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
446
464
  }
447
465
  return result;
448
466
  }};
449
- const receipt = await deploy({api:observed, plan, artifact, artifactSha256:hash(artifact), previousReceipt:state.receipt ?? undefined,
467
+ const receipt = await deploy({api:observed, plan, artifact, artifactSha256:hash(artifact), previousReceipt:state.receipt ?? undefined, pendingUpload:state.pendingUpload,
450
468
  // Migrations run inside this run's state lock: no other deploy of this install is running.
451
469
  createResources:false, uploadWithoutReceipt:true, locked:true, env, fetch, healthOptions, readiness, declaredSecrets,
452
470
  onReceipt: async candidate => { if (candidate.changed || !state.receipt) { state.receipt = candidate; delete state.pendingUpload; delete state.pendingSecret; await save(); } },
@@ -457,7 +475,7 @@ async function deployLocked({api, target, plan, artifact, statePath, env, fetch,
457
475
 
458
476
  /** Independent read-only health of the last owner deployment recorded in the state file. */
459
477
  export async function ownerHealth({api: provider, target, plan, statePath, fetch = globalThis.fetch, healthOptions = {}}) {
460
- const api = withSettledLists(withScopeHints(provider));
478
+ const api = withSettledLists(withScopeHints(provider),{signal:healthOptions.signal});
461
479
  validatePlan(plan); assertOwnerNames(target, plan);
462
480
  const state = await readOwnerState(statePath, target);
463
481
  assert(state.receipt, 'missing-owner-receipt');
@@ -27,7 +27,9 @@ export async function providerResponse({send, method, timeoutMs, callerSignal, r
27
27
  const attemptSignal = firstRead ? AbortSignal.any([signal, firstRead.signal]) : signal;
28
28
  let readingBody = false, response;
29
29
  try {
30
+ attemptSignal.throwIfAborted();
30
31
  response = await send(attemptSignal);
32
+ attemptSignal.throwIfAborted();
31
33
  clearTimeout(timer);
32
34
  // A retried delete can observe the first attempt's committed deletion.
33
35
  if (removalReplay && method === 'DELETE' && attempt > 1 && response.status === 404) {