@evomap/evolver-proxy 2.0.0-beta.1 → 2.0.0-beta.11

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 (43) hide show
  1. package/dist/bin/evolver-proxy.d.ts +69 -7
  2. package/dist/bin/evolver-proxy.js +437 -91
  3. package/dist/bin/proxySettings.d.ts +2 -0
  4. package/dist/bin/proxySettings.js +8 -1
  5. package/dist/daemon/collaborationFacade.d.ts +56 -0
  6. package/dist/daemon/collaborationFacade.js +877 -0
  7. package/dist/daemon/proxyDaemon.d.ts +4 -0
  8. package/dist/daemon/proxyDaemon.js +130 -2
  9. package/dist/daemon/selectHub.js +17 -1
  10. package/dist/index.d.ts +2 -1
  11. package/dist/index.js +2 -1
  12. package/dist/lifecycle/legacyNodeId.d.ts +11 -13
  13. package/dist/lifecycle/legacyNodeId.js +35 -20
  14. package/dist/llm/traceControl.js +1 -1
  15. package/dist/private/accountAssetCompatibility.d.ts +28 -0
  16. package/dist/private/accountAssetCompatibility.js +196 -0
  17. package/dist/private/adapterLoader.d.ts +19 -2
  18. package/dist/private/adapterLoader.js +78 -4
  19. package/dist/router/messagesRoute.d.ts +13 -0
  20. package/dist/router/messagesRoute.js +56 -0
  21. package/dist/selfUpdate/executor.d.ts +10 -5
  22. package/dist/selfUpdate/executor.js +81 -6
  23. package/dist/selfUpdate/failureCodes.d.ts +6 -0
  24. package/dist/selfUpdate/failureCodes.js +6 -0
  25. package/dist/selfUpdate/index.d.ts +4 -1
  26. package/dist/selfUpdate/index.js +4 -1
  27. package/dist/selfUpdate/lastUpdate.d.ts +3 -1
  28. package/dist/selfUpdate/lastUpdate.js +37 -6
  29. package/dist/selfUpdate/releaseBinary.d.ts +10 -0
  30. package/dist/selfUpdate/releaseBinary.js +43 -6
  31. package/dist/selfUpdate/transaction.d.ts +109 -0
  32. package/dist/selfUpdate/transaction.js +1174 -0
  33. package/dist/selfUpdate/unixController.d.ts +15 -0
  34. package/dist/selfUpdate/unixController.js +186 -0
  35. package/dist/selfUpdate/version.d.ts +6 -2
  36. package/dist/selfUpdate/version.js +5 -3
  37. package/dist/selfUpdate/windowsController.d.ts +23 -0
  38. package/dist/selfUpdate/windowsController.js +274 -0
  39. package/dist/selfUpdate/windowsUpdater.d.ts +79 -0
  40. package/dist/selfUpdate/windowsUpdater.js +715 -0
  41. package/dist/sync/engine.d.ts +6 -5
  42. package/dist/sync/engine.js +102 -58
  43. package/package.json +8 -3
@@ -1,5 +1,6 @@
1
- import type { hub as hubNs } from '@evomap/evolver-core';
1
+ import { hub as hubNs } from '@evomap/evolver-core';
2
2
  import type { HelloResult, HeartbeatOptions, HeartbeatResult } from '../lifecycle/manager.js';
3
+ import { type PrivateAccountAssetHub, type PrivateCompatibilityFetch } from './accountAssetCompatibility.js';
3
4
  export type PrivateHubWithLifecycle = hubNs.HubCapability & {
4
5
  hello(opts: {
5
6
  rotate: boolean;
@@ -7,6 +8,7 @@ export type PrivateHubWithLifecycle = hubNs.HubCapability & {
7
8
  }): Promise<HelloResult>;
8
9
  heartbeat(opts?: HeartbeatOptions): Promise<HeartbeatResult>;
9
10
  };
11
+ export type PrivateProxyHub = PrivateHubWithLifecycle & PrivateAccountAssetHub;
10
12
  interface PrivateSsoExchange {
11
13
  identity: () => {
12
14
  subject: string;
@@ -27,11 +29,21 @@ export interface ConnectPrivateHubOptions {
27
29
  senderId: () => string | undefined;
28
30
  env?: Record<string, string | undefined>;
29
31
  now?: () => number;
32
+ /** One-shot invitation token (evoinv_…) — preferred over the SSO bearer for token_required hubs. */
33
+ invitationToken?: string;
34
+ /** Ready credential from the standard Private Hub onboarding store. */
35
+ nodeSecret?: string;
36
+ fetchFn?: PrivateCompatibilityFetch;
30
37
  }
31
38
  type DynamicImporter = (specifier: string) => Promise<unknown>;
32
39
  export interface PrivateProxyHubRuntime {
33
- hub: PrivateHubWithLifecycle;
40
+ hub: PrivateProxyHub;
34
41
  auth: hubNs.AuthProvider;
42
+ /** Enrollment-aware lifecycle entrypoint. Ready node_secret credentials must not re-run hello. */
43
+ hello(opts: {
44
+ rotate: boolean;
45
+ evolverVersion?: string;
46
+ }): Promise<HelloResult>;
35
47
  }
36
48
  export interface ConnectPrivateProxyHubOptions {
37
49
  hubUrl: string;
@@ -39,8 +51,13 @@ export interface ConnectPrivateProxyHubOptions {
39
51
  env: Record<string, string | undefined>;
40
52
  now?: () => number;
41
53
  importer?: DynamicImporter;
54
+ fetchFn?: PrivateCompatibilityFetch;
42
55
  }
43
56
  export declare function resolvePrivateEnterpriseToken(env: Record<string, string | undefined>): string | undefined;
57
+ /** One-shot invitation token (evoinv_…), matching the hub's official onboarding script (A2A_INVITATION_TOKEN).
58
+ * Preferred over the enterprise token for the default token_required enrollment mode. */
59
+ export declare function resolvePrivateInvitationToken(env: Record<string, string | undefined>): string | undefined;
60
+ export declare function resolvePrivateNodeSecret(env: Record<string, string | undefined>): string | undefined;
44
61
  export declare function resolvePrivateEnterpriseSubject(env: Record<string, string | undefined>): string;
45
62
  export declare function connectPrivateProxyHub(opts: ConnectPrivateProxyHubOptions): Promise<PrivateProxyHubRuntime>;
46
63
  export {};
@@ -1,14 +1,29 @@
1
+ import { hub as hubNs } from '@evomap/evolver-core';
2
+ import { withPrivateAccountAssetCompatibility, } from './accountAssetCompatibility.js';
1
3
  const DEFAULT_PRIVATE_ADAPTER_MODULE = '@evomap/evolver-adapter-private';
2
4
  export function resolvePrivateEnterpriseToken(env) {
3
5
  return firstEnv(env, 'EVOMAP_ENTERPRISE_TOKEN', 'EVOMAP_PRIVATE_HUB_TOKEN', 'PHUB_ENTERPRISE_TOKEN', 'PRIVATE_HUB_ENTERPRISE_TOKEN');
4
6
  }
7
+ /** One-shot invitation token (evoinv_…), matching the hub's official onboarding script (A2A_INVITATION_TOKEN).
8
+ * Preferred over the enterprise token for the default token_required enrollment mode. */
9
+ export function resolvePrivateInvitationToken(env) {
10
+ return firstEnv(env, 'A2A_INVITATION_TOKEN');
11
+ }
12
+ export function resolvePrivateNodeSecret(env) {
13
+ return firstEnv(env, 'EVOMAP_NODE_SECRET', 'A2A_NODE_SECRET');
14
+ }
5
15
  export function resolvePrivateEnterpriseSubject(env) {
6
16
  return firstEnv(env, 'EVOMAP_ENTERPRISE_SUBJECT', 'EVOMAP_PRIVATE_SUBJECT', 'PHUB_ENTERPRISE_SUBJECT', 'USER') ?? 'evolver-proxy';
7
17
  }
8
18
  export async function connectPrivateProxyHub(opts) {
19
+ const invitationToken = resolvePrivateInvitationToken(opts.env);
9
20
  const token = resolvePrivateEnterpriseToken(opts.env);
10
- if (!token) {
11
- throw new Error('EVOMAP_HUB_MODE=private 需要 EVOMAP_ENTERPRISE_TOKEN(也兼容 EVOMAP_PRIVATE_HUB_TOKEN / PHUB_ENTERPRISE_TOKEN)');
21
+ const nodeSecret = resolvePrivateNodeSecret(opts.env);
22
+ if (nodeSecret && !isNodeSecret(nodeSecret)) {
23
+ throw new Error('Private Hub node_secret 必须是 64 位十六进制字符串');
24
+ }
25
+ if (!token && !invitationToken && !nodeSecret) {
26
+ throw new Error('EVOMAP_HUB_MODE=private 需要 A2A_NODE_SECRET / EVOMAP_NODE_SECRET、A2A_INVITATION_TOKEN 或 EVOMAP_ENTERPRISE_TOKEN');
12
27
  }
13
28
  const moduleName = opts.env['EVOMAP_PRIVATE_ADAPTER_MODULE']?.trim() || DEFAULT_PRIVATE_ADAPTER_MODULE;
14
29
  const connectPrivateHub = await loadConnectPrivateHub(moduleName, opts.importer ?? ((specifier) => import(specifier)));
@@ -21,12 +36,33 @@ export async function connectPrivateProxyHub(opts) {
21
36
  now,
22
37
  sso: {
23
38
  identity: () => ({ subject }),
24
- exchange: async () => ({ token }),
39
+ exchange: async () => ({ token: token ?? nodeSecret ?? '' }),
25
40
  now,
26
41
  },
42
+ ...(nodeSecret ? { nodeSecret } : {}),
43
+ ...(!nodeSecret && invitationToken ? { invitationToken } : {}),
44
+ ...(opts.fetchFn ? { fetchFn: opts.fetchFn } : {}),
27
45
  });
28
46
  assertPrivateLifecycle(hub, moduleName);
29
- return { hub, auth };
47
+ if (nodeSecret)
48
+ await adoptReadyNodeSecret(auth, nodeSecret);
49
+ if (!hub.agentDirectory) {
50
+ hub.agentDirectory = hubNs.unsupportedAgentDirectoryCapability('private_hub_agent_directory_not_supported');
51
+ }
52
+ const compatibleHub = withPrivateAccountAssetCompatibility(hub, {
53
+ baseUrl: opts.hubUrl,
54
+ auth,
55
+ senderId: opts.senderId,
56
+ env: opts.env,
57
+ ...(opts.fetchFn ? { fetchFn: opts.fetchFn } : {}),
58
+ });
59
+ return {
60
+ hub: compatibleHub,
61
+ auth,
62
+ hello: nodeSecret
63
+ ? async (helloOpts) => await helloWithReadyPrivateCredential(compatibleHub, auth, nodeSecret, opts.senderId, helloOpts)
64
+ : (helloOpts) => compatibleHub.hello(helloOpts),
65
+ };
30
66
  }
31
67
  async function loadConnectPrivateHub(moduleName, importer) {
32
68
  let loaded;
@@ -49,6 +85,44 @@ function assertPrivateLifecycle(hub, moduleName) {
49
85
  throw new Error(`${moduleName} 的 hub 缺少 hello/heartbeat lifecycle 方法,无法接入 evolver-proxy`);
50
86
  }
51
87
  }
88
+ async function adoptReadyNodeSecret(auth, nodeSecret) {
89
+ const candidate = auth;
90
+ if (typeof candidate.adoptNodeSecret === 'function') {
91
+ candidate.adoptNodeSecret.call(auth, nodeSecret);
92
+ }
93
+ if (!await authenticatesWithNodeSecret(auth, nodeSecret)) {
94
+ throw new Error('private Hub adapter cannot activate the configured node_secret');
95
+ }
96
+ }
97
+ async function helloWithReadyPrivateCredential(hub, auth, nodeSecret, senderId, opts) {
98
+ if (await authenticatesWithNodeSecret(auth, nodeSecret))
99
+ return readyPrivateHello(senderId);
100
+ return await hub.hello(opts);
101
+ }
102
+ async function authenticatesWithNodeSecret(auth, nodeSecret) {
103
+ const signed = await auth.authenticate({ method: 'GET', path: '/a2a/assets/published-by-me' });
104
+ const authorization = headerValue(signed.headers, 'authorization');
105
+ const bodySecret = signed.bodyFields?.['node_secret'];
106
+ return authorization === `Bearer ${nodeSecret}` || bodySecret === nodeSecret;
107
+ }
108
+ function headerValue(headers, name) {
109
+ const lower = name.toLowerCase();
110
+ for (const [key, value] of Object.entries(headers)) {
111
+ if (key.toLowerCase() === lower)
112
+ return value;
113
+ }
114
+ return undefined;
115
+ }
116
+ function trimmedSenderId(senderId) {
117
+ return senderId()?.trim() || undefined;
118
+ }
119
+ function readyPrivateHello(senderId) {
120
+ const nodeId = trimmedSenderId(senderId);
121
+ return { ok: true, ...(nodeId ? { nodeId } : {}) };
122
+ }
123
+ function isNodeSecret(value) {
124
+ return /^[a-f0-9]{64}$/i.test(value);
125
+ }
52
126
  function firstEnv(env, ...keys) {
53
127
  for (const key of keys) {
54
128
  const value = env[key]?.trim();
@@ -112,6 +112,19 @@ export interface MessagesResponse {
112
112
  }
113
113
  export declare function captureTraceMetadata(value: unknown, env?: NodeJS.ProcessEnv): unknown;
114
114
  export declare function resolveTierModels(env?: NodeJS.ProcessEnv): Partial<Record<Tier, string>>;
115
+ export type TierConfigWarningReason = 'missing_tier_models' | 'duplicate_tier_models' | 'all_tier_models_same';
116
+ export interface TierConfigWarning {
117
+ event: 'router_config_warning';
118
+ reason: TierConfigWarningReason;
119
+ message: string;
120
+ configured_tiers: Tier[];
121
+ missing_tiers?: Tier[];
122
+ duplicate_models?: Array<{
123
+ model: string;
124
+ tiers: Tier[];
125
+ }>;
126
+ }
127
+ export declare function detectTierModelConfigWarnings(models: Partial<Record<Tier, string>>): TierConfigWarning[];
115
128
  interface ClaudeId {
116
129
  family: string;
117
130
  major: number;
@@ -34,6 +34,58 @@ export function resolveTierModels(env = process.env) {
34
34
  out.expensive = env['EVOMAP_MODEL_EXPENSIVE'];
35
35
  return out;
36
36
  }
37
+ const TIER_ORDER = ['cheap', 'mid', 'expensive'];
38
+ export function detectTierModelConfigWarnings(models) {
39
+ const configuredTiers = TIER_ORDER.filter((tier) => {
40
+ const model = models[tier];
41
+ return typeof model === 'string' && model.length > 0;
42
+ });
43
+ if (configuredTiers.length === 0)
44
+ return [];
45
+ const warnings = [];
46
+ const missingTiers = TIER_ORDER.filter((tier) => !configuredTiers.includes(tier));
47
+ if (missingTiers.length > 0) {
48
+ warnings.push({
49
+ event: 'router_config_warning',
50
+ reason: 'missing_tier_models',
51
+ message: 'Router tier config is partial; unset tiers will pass the client model through.',
52
+ configured_tiers: configuredTiers,
53
+ missing_tiers: missingTiers,
54
+ });
55
+ }
56
+ const byModel = new Map();
57
+ for (const tier of configuredTiers) {
58
+ const model = models[tier];
59
+ if (!model)
60
+ continue;
61
+ byModel.set(model, [...(byModel.get(model) ?? []), tier]);
62
+ }
63
+ const duplicateModels = Array.from(byModel.entries())
64
+ .filter(([, tiers]) => tiers.length > 1)
65
+ .map(([model, tiers]) => ({ model, tiers }));
66
+ const allSame = configuredTiers.length === TIER_ORDER.length
67
+ && duplicateModels.length === 1
68
+ && duplicateModels[0].tiers.length === TIER_ORDER.length;
69
+ if (allSame) {
70
+ warnings.push({
71
+ event: 'router_config_warning',
72
+ reason: 'all_tier_models_same',
73
+ message: 'All router tiers resolve to the same model; routing will still run but cannot change cost/latency tiers.',
74
+ configured_tiers: configuredTiers,
75
+ duplicate_models: duplicateModels,
76
+ });
77
+ }
78
+ else if (duplicateModels.length > 0) {
79
+ warnings.push({
80
+ event: 'router_config_warning',
81
+ reason: 'duplicate_tier_models',
82
+ message: 'Multiple router tiers resolve to the same model; routing will still run but tier separation is degraded.',
83
+ configured_tiers: configuredTiers,
84
+ duplicate_models: duplicateModels,
85
+ });
86
+ }
87
+ return warnings;
88
+ }
37
89
  export function parseClaudeId(modelId) {
38
90
  if (typeof modelId !== 'string')
39
91
  return null;
@@ -386,6 +438,10 @@ export function buildMessagesHandler(opts) {
386
438
  const log = opts.logger ?? console;
387
439
  const env = opts.env ?? process.env;
388
440
  const enabled = typeof opts.routerEnabled === 'boolean' ? opts.routerEnabled : env['EVOMAP_ROUTER_ENABLED'] === '1';
441
+ if (enabled) {
442
+ for (const warning of detectTierModelConfigWarnings(resolveTierModels(env)))
443
+ log.warn?.(j(warning));
444
+ }
389
445
  // Native body capture defaults to v1-compatible full trace mode. Operators that need metadata-only rows must
390
446
  // explicitly disable it (a compliance decision; see bodyCapture.ts and docs/trace-body-capture.md).
391
447
  const captureBodies = captureBodiesEnabled(env);
@@ -1,8 +1,9 @@
1
1
  import { ops } from '@evomap/evolver-core';
2
2
  import { type SelfUpdateFailureCode } from './failureCodes.js';
3
+ import type { DurableSelfUpdateSession } from './transaction.js';
3
4
  type DownloadedArtifact = ops.DownloadedArtifact;
4
5
  /** Structured outcome codes — reported to telemetry; the hub sees WHY an update did/didn't apply. */
5
- export type SelfUpdateOutcome = 'applied' | 'noop' | 'rejected_decision' | 'rejected_verification' | 'download_failed' | 'replace_failed' | 'already_in_progress' | 'disabled';
6
+ export type SelfUpdateOutcome = 'applied' | 'noop' | 'rejected_decision' | 'rejected_verification' | 'download_failed' | 'replace_failed' | 'restart_failed' | 'rollback_failed' | 'already_in_progress' | 'disabled';
6
7
  export interface SelfUpdateResult {
7
8
  outcome: SelfUpdateOutcome;
8
9
  reason: string;
@@ -13,13 +14,15 @@ export interface SelfUpdateResult {
13
14
  /**
14
15
  * Which download path produced the staged binary: `'binary'` is the normal
15
16
  * precompiled-asset happy path, `'tarball'` means the binary download failed
16
- * and Channel 1b (release `.tar.gz`) fallback was used. The verifyManifest
17
+ * and Channel 1b (release `.tar.gz`) fallback was used. The selected-artifact
17
18
  * gate ran in BOTH cases, so apply-semantics are identical, but "tarball
18
19
  * used in production" is a useful CDN/rate-limit signal for the hub.
19
20
  * Persisted into `last_update.json` (lastUpdate.LastUpdatePayload.applied_via)
20
21
  * on success so the hub can observe the channel directly.
21
22
  */
22
23
  appliedVia?: 'binary' | 'tarball';
24
+ /** Durable installs are not successful until the relaunched daemon completes startup health checks. */
25
+ confirmationPending?: true;
23
26
  }
24
27
  /** The hub's force_update directive (inbound message payload). */
25
28
  export interface ForceUpdateDirective {
@@ -36,7 +39,7 @@ export interface ForceUpdateDirective {
36
39
  export interface DownloadResult {
37
40
  /** Where the new version was staged (e.g. a tmp dir). Passed to atomicReplace on success. */
38
41
  stagedPath: string;
39
- /** The downloaded artifacts (bytes or precomputed sha256) for verifyManifest. */
42
+ /** Exactly one selected artifact (bytes or precomputed sha256) for verification. */
40
43
  artifacts: readonly DownloadedArtifact[];
41
44
  /**
42
45
  * Which channel actually produced the staged bytes — defaults to `'binary'`
@@ -63,8 +66,10 @@ export interface SelfUpdateDeps {
63
66
  download: (targetVersion: string, directive: ForceUpdateDirective) => Promise<DownloadResult>;
64
67
  /** Atomically replace the install tree with the staged path (preserving node_modules/.env/etc). Throws on fail. */
65
68
  atomicReplace: (stagedPath: string) => Promise<void>;
69
+ /** Optional durable transaction: cross-process lock + journal + backup + recovery-aware install. */
70
+ beginTransaction?: (targetVersion: string) => Promise<DurableSelfUpdateSession>;
66
71
  /** Signal a restart so the supervisor relaunches the new version. v1 convention: process.exit(78). */
67
- restart: () => void;
72
+ restart: () => void | Promise<void>;
68
73
  /** Optional Ed25519 public key (PEM / raw base64). When set, an unsigned/badly-signed manifest is REJECTED. */
69
74
  publicKey?: string;
70
75
  /** Best-effort telemetry sink for the structured outcome (never throws into the update path). */
@@ -80,7 +85,7 @@ export declare function _resetSelfUpdateMutex(): void;
80
85
  * 2. decideUpdate (pure): reject bad manifests, NOOP when already satisfied (no download, no restart).
81
86
  * 3. mutex: exactly one execution; concurrent callers get `already_in_progress` and touch no disk.
82
87
  * 4. download the staged release.
83
- * 5. verifyManifest (pure) — THE GATE. Fail → no write, no restart, `rejected_verification`.
88
+ * 5. verifySelectedManifestArtifact (pure) — THE GATE. Fail → no write, no restart.
84
89
  * 6. atomicReplace, then restart(). Only reached after verification passed.
85
90
  *
86
91
  * Never throws: every failure becomes a structured SelfUpdateResult so the daemon can report it and keep running
@@ -4,7 +4,8 @@
4
4
  // shells out or touches a real install tree by accident.
5
5
  //
6
6
  // THE HARD GATE (verify-before-apply, non-negotiable): after download and BEFORE any filesystem write or restart,
7
- // the executor calls the PURE core verifyManifest. If verification fails — bad sha256, missing/invalid signature
7
+ // the executor calls the PURE core verifySelectedManifestArtifact. If verification fails — bad sha256,
8
+ // missing/invalid signature
8
9
  // when a key is configured, anything — the executor writes NOTHING, restarts NOTHING, and returns a structured
9
10
  // failure. The old version stays intact and runnable. A compromised hub cannot turn this channel into fleet RCE.
10
11
  //
@@ -12,7 +13,7 @@
12
13
  // once. The second caller short-circuits with `already_in_progress` and performs no I/O.
13
14
  import { ops } from '@evomap/evolver-core';
14
15
  import { SELF_UPDATE_FAILURE_CODES, classifySelfUpdateError, codeForDecisionReject, } from './failureCodes.js';
15
- const { decideUpdate, verifyManifest } = ops;
16
+ const { decideUpdate, verifySelectedManifestArtifact } = ops;
16
17
  // Process-level mutex. Module scope is correct: there is one daemon per process, and v1's _forceUpdateInFlight had
17
18
  // the same lifetime. Guards against two force_update envelopes (or a heartbeat-driven + mailbox-driven trigger)
18
19
  // racing the same upgrade and replacing files twice / double-restarting.
@@ -38,7 +39,7 @@ function report(deps, result) {
38
39
  * 2. decideUpdate (pure): reject bad manifests, NOOP when already satisfied (no download, no restart).
39
40
  * 3. mutex: exactly one execution; concurrent callers get `already_in_progress` and touch no disk.
40
41
  * 4. download the staged release.
41
- * 5. verifyManifest (pure) — THE GATE. Fail → no write, no restart, `rejected_verification`.
42
+ * 5. verifySelectedManifestArtifact (pure) — THE GATE. Fail → no write, no restart.
42
43
  * 6. atomicReplace, then restart(). Only reached after verification passed.
43
44
  *
44
45
  * Never throws: every failure becomes a structured SelfUpdateResult so the daemon can report it and keep running
@@ -103,13 +104,29 @@ export async function executeForceUpdate(directive, deps) {
103
104
  }
104
105
  inFlight = true;
105
106
  const targetVersion = decision.targetVersion ?? manifest?.version ?? '';
107
+ let transaction;
106
108
  try {
109
+ if (deps.beginTransaction) {
110
+ try {
111
+ transaction = await deps.beginTransaction(targetVersion);
112
+ }
113
+ catch (err) {
114
+ const classified = classifySelfUpdateError(err, SELF_UPDATE_FAILURE_CODES.UPDATE_LOCKED);
115
+ return report(deps, {
116
+ outcome: classified.failureCode === SELF_UPDATE_FAILURE_CODES.UPDATE_LOCKED ? 'already_in_progress' : 'replace_failed',
117
+ reason: classified.detail,
118
+ failureCode: classified.failureCode,
119
+ targetVersion,
120
+ });
121
+ }
122
+ }
107
123
  // 4. Download the staged release.
108
124
  let dl;
109
125
  try {
110
126
  dl = await deps.download(targetVersion, effectiveDirective);
111
127
  }
112
128
  catch (err) {
129
+ await transaction?.abort(SELF_UPDATE_FAILURE_CODES.DOWNLOAD_FAILED).catch(() => { });
113
130
  const classified = classifySelfUpdateError(err, SELF_UPDATE_FAILURE_CODES.DOWNLOAD_FAILED);
114
131
  return report(deps, {
115
132
  outcome: 'download_failed',
@@ -118,9 +135,25 @@ export async function executeForceUpdate(directive, deps) {
118
135
  targetVersion,
119
136
  });
120
137
  }
138
+ if (transaction) {
139
+ try {
140
+ dl = await transaction.adoptDownloaded(dl);
141
+ }
142
+ catch (err) {
143
+ await transaction.abort(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED).catch(() => { });
144
+ const classified = classifySelfUpdateError(err, SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED);
145
+ return report(deps, {
146
+ outcome: 'replace_failed',
147
+ reason: classified.detail,
148
+ failureCode: classified.failureCode,
149
+ targetVersion,
150
+ });
151
+ }
152
+ }
121
153
  // 5. THE GATE: verify the downloaded bytes against the (optionally signed) manifest BEFORE any write.
122
- const verification = verifyManifest(manifest, dl.artifacts, ...(deps.publicKey ? [deps.publicKey] : []));
154
+ const verification = verifySelectedManifestArtifact(manifest, dl.artifacts, ...(deps.publicKey ? [deps.publicKey] : []));
123
155
  if (!verification.ok) {
156
+ await transaction?.abort(SELF_UPDATE_FAILURE_CODES.REJECTED_VERIFICATION).catch(() => { });
124
157
  // Verification failed → write NOTHING, restart NOTHING. Old version stays intact and runnable.
125
158
  return report(deps, {
126
159
  outcome: 'rejected_verification',
@@ -129,9 +162,25 @@ export async function executeForceUpdate(directive, deps) {
129
162
  targetVersion,
130
163
  });
131
164
  }
165
+ try {
166
+ await transaction?.markVerified(dl.artifacts);
167
+ }
168
+ catch (err) {
169
+ await transaction?.abort(SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED).catch(() => { });
170
+ const classified = classifySelfUpdateError(err, SELF_UPDATE_FAILURE_CODES.REPLACE_FAILED);
171
+ return report(deps, {
172
+ outcome: 'replace_failed',
173
+ reason: classified.detail,
174
+ failureCode: classified.failureCode,
175
+ targetVersion,
176
+ });
177
+ }
132
178
  // 6. Verified. Atomic replace, then signal restart. A replace failure leaves the old version intact.
133
179
  try {
134
- await deps.atomicReplace(dl.stagedPath);
180
+ if (transaction)
181
+ await transaction.install();
182
+ else
183
+ await deps.atomicReplace(dl.stagedPath);
135
184
  }
136
185
  catch (err) {
137
186
  const classified = classifySelfUpdateError(err, SELF_UPDATE_FAILURE_CODES.COPY_FAILED);
@@ -147,12 +196,38 @@ export async function executeForceUpdate(directive, deps) {
147
196
  reason: 'verified_and_replaced',
148
197
  targetVersion,
149
198
  appliedVia: dl.appliedVia ?? 'binary',
199
+ ...(transaction ? { confirmationPending: true } : {}),
150
200
  };
151
201
  report(deps, result);
152
- deps.restart(); // v1 convention: exit(78) → supervisor relaunches the new version.
202
+ try {
203
+ await transaction?.markRestartRequested();
204
+ await deps.restart(); // v1 convention: exit(78) → supervisor relaunches the new version.
205
+ }
206
+ catch (err) {
207
+ const classified = classifySelfUpdateError(err, SELF_UPDATE_FAILURE_CODES.RESTART_FAILED);
208
+ try {
209
+ await transaction?.rollback(classified.failureCode);
210
+ }
211
+ catch (rollbackError) {
212
+ const rollback = classifySelfUpdateError(rollbackError, SELF_UPDATE_FAILURE_CODES.ROLLBACK_FAILED);
213
+ return report(deps, {
214
+ outcome: 'rollback_failed',
215
+ reason: rollback.detail,
216
+ failureCode: rollback.failureCode,
217
+ targetVersion,
218
+ });
219
+ }
220
+ return report(deps, {
221
+ outcome: 'restart_failed',
222
+ reason: classified.detail,
223
+ failureCode: classified.failureCode,
224
+ targetVersion,
225
+ });
226
+ }
153
227
  return result;
154
228
  }
155
229
  finally {
230
+ await transaction?.release().catch(() => { });
156
231
  // Released so a later legitimate update (after a failed attempt) can proceed. On the success path the process
157
232
  // is exiting anyway; releasing is harmless and keeps the mutex honest if restart() is a test fake that returns.
158
233
  inFlight = false;
@@ -17,6 +17,12 @@ export declare const SELF_UPDATE_FAILURE_CODES: Readonly<{
17
17
  readonly FALLBACK_DOWNLOAD_FAILED: "fallback_download_failed";
18
18
  readonly FALLBACK_EXTRACT_FAILED: "fallback_extract_failed";
19
19
  readonly FALLBACK_MISSING_BINARY: "fallback_missing_binary";
20
+ readonly UPDATE_LOCKED: "update_locked";
21
+ readonly RECOVERY_REQUIRED: "recovery_required";
22
+ readonly UNSAFE_UPDATE_PATH: "unsafe_update_path";
23
+ readonly RESTART_FAILED: "restart_failed";
24
+ readonly READ_BACK_FAILED: "read_back_failed";
25
+ readonly ROLLBACK_FAILED: "rollback_failed";
20
26
  }>;
21
27
  export type SelfUpdateFailureCode = typeof SELF_UPDATE_FAILURE_CODES[keyof typeof SELF_UPDATE_FAILURE_CODES];
22
28
  export interface ClassifiedSelfUpdateError {
@@ -22,6 +22,12 @@ export const SELF_UPDATE_FAILURE_CODES = Object.freeze({
22
22
  FALLBACK_DOWNLOAD_FAILED: 'fallback_download_failed',
23
23
  FALLBACK_EXTRACT_FAILED: 'fallback_extract_failed',
24
24
  FALLBACK_MISSING_BINARY: 'fallback_missing_binary',
25
+ UPDATE_LOCKED: 'update_locked',
26
+ RECOVERY_REQUIRED: 'recovery_required',
27
+ UNSAFE_UPDATE_PATH: 'unsafe_update_path',
28
+ RESTART_FAILED: 'restart_failed',
29
+ READ_BACK_FAILED: 'read_back_failed',
30
+ ROLLBACK_FAILED: 'rollback_failed',
25
31
  });
26
32
  export class SelfUpdateFailureError extends Error {
27
33
  failureCode;
@@ -2,4 +2,7 @@ export * from './executor.js';
2
2
  export * from './version.js';
3
3
  export * from './policy.js';
4
4
  export * from './releaseBinary.js';
5
- export * from './failureCodes.js';
5
+ export * from './transaction.js';
6
+ export * from './failureCodes.js';
7
+ export * from './unixController.js';
8
+ export * from './windowsController.js';
@@ -2,4 +2,7 @@ export * from './executor.js';
2
2
  export * from './version.js';
3
3
  export * from './policy.js';
4
4
  export * from './releaseBinary.js';
5
- export * from './failureCodes.js';
5
+ export * from './transaction.js';
6
+ export * from './failureCodes.js';
7
+ export * from './unixController.js';
8
+ export * from './windowsController.js';
@@ -1,5 +1,6 @@
1
1
  import { mailbox } from '@evomap/evolver-core';
2
2
  import type { ForceUpdateDirective, SelfUpdateResult } from './executor.js';
3
+ import type { SelfUpdateRecoveryResult } from './transaction.js';
3
4
  type MailboxStore = mailbox.MailboxStore;
4
5
  type LastUpdateStatus = 'success' | 'failed' | 'skipped' | 'pending';
5
6
  export interface LastUpdatePayload {
@@ -12,7 +13,7 @@ export interface LastUpdatePayload {
12
13
  /**
13
14
  * Which download channel produced the bytes that got applied: `'binary'` is
14
15
  * the precompiled-asset happy path, `'tarball'` means Channel 1b fallback
15
- * (release `.tar.gz`) was used. Persisted on success so the hub can see
16
+ * (release `.tar.gz`) was used. Persisted while confirmation is pending and on success so the hub can see
16
17
  * "primary CDN is degraded — fallback carrying production" without having
17
18
  * to mine telemetry. Absent on non-success or when the executor predates
18
19
  * the appliedVia field.
@@ -36,6 +37,7 @@ export declare function reportPendingSelfUpdateLastUpdate(store: MailboxStore, d
36
37
  fromVersion: string;
37
38
  now?: number;
38
39
  }): boolean;
40
+ export declare function finalizeSelfUpdateRecoveryLastUpdate(store: MailboxStore, recovery: SelfUpdateRecoveryResult, now?: number): boolean;
39
41
  export declare function lastUpdateFromSelfUpdateResult(directive: ForceUpdateDirective, result: SelfUpdateResult, opts: {
40
42
  fromVersion: string;
41
43
  now: number;
@@ -86,6 +86,37 @@ export function reportPendingSelfUpdateLastUpdate(store, directive, opts = { fro
86
86
  ...(directive.directive_id ? { directive_id: String(directive.directive_id) } : {}),
87
87
  }, now);
88
88
  }
89
+ export function finalizeSelfUpdateRecoveryLastUpdate(store, recovery, now = Date.now()) {
90
+ if (recovery.outcome !== 'confirmed'
91
+ && recovery.outcome !== 'rolled_back'
92
+ && recovery.outcome !== 'blocked')
93
+ return false;
94
+ const toVersion = concreteVersion(recovery.targetVersion);
95
+ const fromVersion = concreteVersion(recovery.fromVersion);
96
+ if (!toVersion)
97
+ return false;
98
+ const current = readPendingLastUpdate(store, now);
99
+ if (current && current.to_version !== toVersion)
100
+ return false;
101
+ const common = {
102
+ to_version: toVersion,
103
+ finished_at: Math.max(now, FINISHED_AT_MIN_MS),
104
+ ...(current?.directive_id ? { directive_id: current.directive_id } : {}),
105
+ ...(current?.from_version ? { from_version: current.from_version } : fromVersion ? { from_version: fromVersion } : {}),
106
+ };
107
+ if (recovery.outcome === 'confirmed') {
108
+ return writeLastUpdate(store, {
109
+ ...common,
110
+ status: 'success',
111
+ ...(current?.applied_via ? { applied_via: current.applied_via } : {}),
112
+ }, now);
113
+ }
114
+ return writeLastUpdate(store, {
115
+ ...common,
116
+ status: 'failed',
117
+ error: clampString(hubNs.redactString(`${recovery.failureCode ?? 'self_update_recovery_failed'}: ${recovery.outcome}`), LAST_UPDATE_ERROR_MAX),
118
+ }, now);
119
+ }
89
120
  export function lastUpdateFromSelfUpdateResult(directive, result, opts) {
90
121
  if (result.outcome === 'already_in_progress' || result.outcome === 'disabled')
91
122
  return undefined;
@@ -94,11 +125,11 @@ export function lastUpdateFromSelfUpdateResult(directive, result, opts) {
94
125
  return undefined;
95
126
  const base = {
96
127
  to_version: toVersion,
97
- status: statusForOutcome(result.outcome),
128
+ status: statusForResult(result),
98
129
  finished_at: Math.max(opts.now, FINISHED_AT_MIN_MS),
99
130
  ...(directive.directive_id ? { directive_id: String(directive.directive_id) } : {}),
100
131
  };
101
- if (base.status === 'success') {
132
+ if (base.status === 'success' || base.status === 'pending') {
102
133
  return {
103
134
  ...base,
104
135
  from_version: clampString(opts.fromVersion, LAST_UPDATE_FROM_VERSION_MAX),
@@ -114,10 +145,10 @@ export function lastUpdateFromSelfUpdateResult(directive, result, opts) {
114
145
  }
115
146
  return base;
116
147
  }
117
- function statusForOutcome(outcome) {
118
- if (outcome === 'applied')
119
- return 'success';
120
- if (outcome === 'noop')
148
+ function statusForResult(result) {
149
+ if (result.outcome === 'applied')
150
+ return result.confirmationPending ? 'pending' : 'success';
151
+ if (result.outcome === 'noop')
121
152
  return 'skipped';
122
153
  return 'failed';
123
154
  }
@@ -11,8 +11,18 @@ export interface ReleaseBinaryOptions {
11
11
  targetPath?: string;
12
12
  processExecPath?: string;
13
13
  requireSignedManifest?: boolean;
14
+ maxPrimaryBinaryBytes?: number;
14
15
  maxExtractedTarballBytes?: number;
15
16
  }
17
+ /**
18
+ * Hard ceiling for primary release binaries. The binary is buffered before its
19
+ * manifest hash is verified, so an unbounded response could exhaust memory
20
+ * before the verification gate runs. 128MiB leaves headroom above current
21
+ * single-platform binaries while bounding that pre-verification allocation.
22
+ */
23
+ export declare const MAX_PRIMARY_BINARY_BYTES: number;
24
+ /** Release metadata is untrusted and buffered before parsing or verification. */
25
+ export declare const MAX_RELEASE_METADATA_BYTES: number;
16
26
  /**
17
27
  * Hard ceiling for Channel 1b tarball downloads. A compromised/corrupt release
18
28
  * could advertise a multi-GB tar.gz and OOM us because tarballBytes is buffered