@revoengine/cli 1.0.21 → 1.0.22

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.
package/README.md CHANGED
@@ -433,7 +433,7 @@ revo schedules push --all --yes --force
433
433
 
434
434
  `--force` permits adopting a missing Schedule baseline or overwriting reviewed target drift. It also approves a reviewed transition between Job Template and Materialized View targets under one Schedule Stable Key. Materialized View refresh Schedules are included with the other Schedules and identify their Database View by Stable Key and refresh mode, never by a source UUID. User-managed `JOB_TEMPLATE` and `PLATFORM_OPERATION` schedules of kind `refresh_materialized_view` are supported. Other platform operations, `AGENT`, and system-managed Schedules are excluded; `--strict` treats exclusions as incomplete coverage.
435
435
 
436
- Pull initializes each Schedule's editable activation candidate from the source. A new target Schedule is created inactive, while a configuration update preserves its target activation state. `schedules push --all --yes --activate` activates only candidates created or updated and verified during that push; unchanged Schedules are not activated. Interactive activation asks for a second confirmation. Repository `deploy` and named `migrate` leave this activation step to the dedicated command.
436
+ Pull initializes each Schedule's editable activation candidate from the source. A new target Schedule is created inactive, while a configuration update preserves its target activation state. `activationCandidate` records the desired active state. Plans report activation-only differences as `activation-drift`, including without a target lock baseline; repository plans mark them as pending changes, and strict plans or deployment verification do not report convergence until they are aligned. `schedules push --all --yes --activate` aligns verified new, updated and otherwise unchanged Schedules with manifest activation intent, including disabling them. Failed configuration preflight skips activation; changed definitions or dependencies block activation. Interactive activation asks for a second confirmation. Repository `deploy` and named `migrate` leave this activation step to the dedicated command.
437
437
 
438
438
  Use `--project` to select a saved project explicitly (`--env` remains a compatible alias):
439
439
 
@@ -495,7 +495,7 @@ Resource plans support `--json` for automation and generally support `--strict`
495
495
  - `--force` approves only explicitly supported risky or drifted operations; it is not a universal bypass.
496
496
  - Writes resolve the target UUID and version immediately before mutation and verify the portable result afterward.
497
497
  - Stable Keys cross environments; source UUIDs, versions, members, users, ACLs, and other target-local identities do not.
498
- - New Schedules and Events are created inactive; ordinary updates preserve target activation. Dedicated `schedules push --all --yes --activate` activates only flagged candidates written and verified in that push, not unchanged Schedules. `events push --all --yes --activate` aligns verified Events with manifest activation intent, including disabling them; configuration failures skip Event activation. Interactive activation requires an additional confirmation. `deploy` and `migrate` do not run this activation phase.
498
+ - New Schedules and Events are created inactive; ordinary updates preserve target activation. Dedicated `schedules push --all --yes --activate` aligns manifest activation intent for verified new, updated and otherwise unchanged Schedules, including disabling them. Activation drift is shown by plans and prevents repository strict-plan/deployment convergence until aligned. `events push --all --yes --activate` aligns verified Events with manifest activation intent, including disabling them; configuration failures skip Event activation. Interactive activation requires an additional confirmation. `deploy` and `migrate` do not run this activation phase.
499
499
  - Groups and Role Groups are intentionally late phases because they can affect ownership and access.
500
500
  - Lock data is stored in `.revoengine/revo.lock.json`; API tokens are never persisted in the project.
501
501
 
@@ -622,3 +622,16 @@ Agent `config.memory`, workspace files, conversations, runs, terminal selection,
622
622
  MCP URLs must use public HTTPS without embedded credentials, query or fragment. New authenticated MCP plugins (including inline plugins) require manual target-local authentication setup and the matching Stable Key before deployment. CLI preserves existing target MCP authentication; it neither provisions secrets nor invokes MCP test/sync or an external provider. Unauthenticated MCP definitions can be created normally. Legacy numeric Component revision pins require a portable `componentDigest` before export; Vault-bound tool inputs and instance-specific rollout snapshots are rejected rather than copied.
623
623
 
624
624
  Agent and Agent Plugin synchronization is upsert-only. Repository prune blocks deletion of either family; retained Agents and inline/registry plugin references also protect Components, Groups and Service Accounts from unsafe pruning. Existing Service Account synchronization remains unchanged, including target-local credentials and membership policy.
625
+
626
+
627
+ ### Deployment verification in 1.0.22
628
+
629
+ Portable comparison includes ordinary Component metadata and full structured Database Table / Materialized View index definitions (logical names, methods, expressions, predicates, ordering, null placement, collation, operator classes and included columns). Physical index names, resource IDs and backend-reserved metadata remain instance-local. Older table/view manifests that omitted index settings should be refreshed from the source before promotion.
630
+
631
+ Endpoint and Job Template pins use the API content identity `v1:sha256:<64 lowercase hex characters>`, independently of the configuration hash. Latest bindings explicitly clear old digest pins. Endpoint `pinnedDigest` fingerprints from older CLI versions are upgraded in memory only when their exact local Component source proves the content identity; otherwise re-pull the source definition. Numeric-only Job Template pins remain explicitly unsupported; use a canonical digest pin instead.
632
+
633
+ Schedule and Event activation differences remain pending changes even if their configuration matches. Ordinary deployment preserves activation; use the existing explicit `schedules push --all --yes --activate` or `events push --all --yes --activate` step to align it. Strict plans and final verification cannot report convergence until activation matches. Deprecated Schedule `targetVersion` is reported diagnostically; the backend does not use it to select a Job Template revision.
634
+
635
+ `CUSTOM_NODEJS` deployment verifies runtime availability and the active desired revision after source readback. Automatic deployment waits up to two minutes for readiness; failed attempts, manual activation requirements and unavailable/pending revisions fail verification without adopting a deployment baseline. Re-run after the runtime is ready. Named `env diff/apply` also reports unavailable unchanged custom runtimes and returns an error on unverified writes. Definition synchronization does not invoke provider/plugin tests; component dependencies and their pinned revisions are checked with read-only API calls, including unchanged definitions.
636
+
637
+ Execution options are compared without hiding runtime differences: missing Job Template memory means 256 MB; explicit 128 MB remains distinct. An empty `options.input` overrides legacy `inputs`. Endpoint `memory: null` remains distinct from 32 MB. If the backend substitutes a different value, readback verification fails rather than recording false convergence.
@@ -45,9 +45,12 @@ export type DatabaseSchemaMetadataWritePayload = {
45
45
  export type DatabaseSchemaUpdatePayload = Omit<DatabaseSchemaMetadataWritePayload, 'metadata'> & {
46
46
  name?: string;
47
47
  metadata?: Record<string, unknown>;
48
- category?: string;
48
+ category?: string | null;
49
49
  desc?: string;
50
50
  definition?: Record<string, unknown>[];
51
+ options?: {
52
+ indexes: Record<string, unknown>[];
53
+ };
51
54
  };
52
55
  export type DatabaseSchemaCreatePayload = {
53
56
  name: string;
@@ -57,6 +60,9 @@ export type DatabaseSchemaCreatePayload = {
57
60
  definition?: Record<string, unknown>[];
58
61
  partition?: Record<string, unknown>;
59
62
  parent?: string;
63
+ options?: {
64
+ indexes: Record<string, unknown>[];
65
+ };
60
66
  audit?: false;
61
67
  restricted?: boolean;
62
68
  };
@@ -84,9 +90,8 @@ export type DatabaseViewCreatePayload = {
84
90
  groups: [];
85
91
  uniqueKey?: string[];
86
92
  indexes?: Array<{
87
- columns: Array<{
88
- name: string;
89
- }>;
93
+ [key: string]: unknown;
94
+ columns: Array<Record<string, unknown>>;
90
95
  unique?: boolean;
91
96
  }>;
92
97
  } & ({
@@ -109,9 +114,7 @@ export type DatabaseViewUpdatePayload = {
109
114
  uniqueKey?: string[];
110
115
  indexes?: Array<{
111
116
  name?: string;
112
- columns: Array<{
113
- name: string;
114
- }>;
117
+ columns: Array<Record<string, unknown>>;
115
118
  unique?: boolean;
116
119
  [key: string]: unknown;
117
120
  }>;
@@ -132,6 +135,7 @@ export type EndpointWritePayload = {
132
135
  desc?: string;
133
136
  componentId?: string | null;
134
137
  componentVersion?: number | null;
138
+ componentDigest?: string | null;
135
139
  timeout?: number;
136
140
  path?: string;
137
141
  method?: string;
@@ -251,6 +255,8 @@ export type JobTemplateUpdatePayload = {
251
255
  desc?: string;
252
256
  metadata?: Record<string, unknown>;
253
257
  componentId?: string;
258
+ componentDigest?: string | null;
259
+ componentVersion?: number | null;
254
260
  timeout?: number | null;
255
261
  options?: unknown;
256
262
  inputs?: unknown;
@@ -263,6 +269,8 @@ export type JobTemplateCreatePayload = {
263
269
  desc?: string;
264
270
  metadata: Record<string, unknown>;
265
271
  componentId: string;
272
+ componentDigest?: string | null;
273
+ componentVersion?: number | null;
266
274
  timeout?: number;
267
275
  options?: unknown;
268
276
  inputs?: unknown;
@@ -418,6 +426,13 @@ export declare class RevoClient {
418
426
  activateEndpoint(endpointId: string): Promise<void>;
419
427
  disableEndpoint(endpointId: string): Promise<void>;
420
428
  restoreEndpoint(endpointId: string): Promise<void>;
429
+ resolveComponentDigest(digest: string): Promise<Array<{
430
+ componentId: string;
431
+ digest: string;
432
+ version: number;
433
+ current?: boolean;
434
+ }>>;
435
+ getComponentRuntime(componentId: string): Promise<unknown>;
421
436
  getComponentSnapshotVersion(componentId: string, version: number): Promise<ComponentRecord>;
422
437
  getEditorTypes(requestPath?: string): Promise<unknown>;
423
438
  debugComponent(requestPath: string, body: unknown): Promise<unknown>;
@@ -487,6 +502,7 @@ export declare class RevoClient {
487
502
  createSchedule(body: ScheduleCreatePayload): Promise<ScheduleResponse>;
488
503
  updateSchedule(scheduleId: string, body: ScheduleWritePayload): Promise<ScheduleResponse>;
489
504
  activateSchedule(scheduleId: string): Promise<unknown>;
505
+ disableSchedule(scheduleId: string): Promise<unknown>;
490
506
  listEvents(options?: EventListRequest): Promise<unknown>;
491
507
  listAllEvents({ includeDeleted }?: EventListAllOptions): Promise<{
492
508
  events: EventRecord[];
@@ -1023,6 +1023,15 @@ export class RevoClient {
1023
1023
  spinnerLabel: 'Restoring endpoint',
1024
1024
  });
1025
1025
  }
1026
+ async resolveComponentDigest(digest) {
1027
+ const result = await this.requestData('GET', `/api/v1/component/digest/${encodeURIComponent(digest)}`);
1028
+ if (!Array.isArray(result.data))
1029
+ throw new Error('Incomplete component digest response.');
1030
+ return result.data;
1031
+ }
1032
+ async getComponentRuntime(componentId) {
1033
+ return this.requestData('GET', `/api/v1/component/${encodeURIComponent(componentId)}/runtime`);
1034
+ }
1026
1035
  async getComponentSnapshotVersion(componentId, version) {
1027
1036
  return this.requestData('GET', `/api/v1/activity/${encodeURIComponent(componentId)}/${encodeURIComponent(String(version))}`, { query: { refType: 'COMPONENTS' } });
1028
1037
  }
@@ -1517,6 +1526,11 @@ export class RevoClient {
1517
1526
  spinnerLabel: 'Activating schedule',
1518
1527
  });
1519
1528
  }
1529
+ async disableSchedule(scheduleId) {
1530
+ return this.requestData('POST', `/api/v1/automation/schedule/${scheduleId}/disable`, {
1531
+ spinnerLabel: 'Disabling schedule',
1532
+ });
1533
+ }
1520
1534
  async listEvents(options = {}) {
1521
1535
  return this.requestData('GET', options.path || '/api/v1/automation/event', {
1522
1536
  query: options.query,
@@ -1,3 +1,4 @@
1
+ import { verifyComponentRuntime } from "../component-contract.js";
1
2
  import fs from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import { execFileSync } from 'node:child_process';
@@ -1184,6 +1185,7 @@ async function pushSingleComponent(context, manifestPath, remoteCatalog) {
1184
1185
  });
1185
1186
  throw new Error(`Cannot push ${targetPath}: created component did not verify against local source. Diagnostic: ${logPath}`);
1186
1187
  }
1188
+ await verifyComponentRuntime(client, refreshedRemote, 120_000);
1187
1189
  upsertLockFromRemote(context, refreshedRemote, targetPath, component, context.componentEnvironment);
1188
1190
  const result = { status: 'deployed', targetPath };
1189
1191
  printSyncStatus(println, { status: 'Deployed', direction: 'push', targetPath });
@@ -1206,6 +1208,8 @@ async function pushSingleComponent(context, manifestPath, remoteCatalog) {
1206
1208
  if (!remoteComponentId) {
1207
1209
  throw new Error(`Remote component matched by ${identityDescription(identity)} "${identityKey}" has no componentId.`);
1208
1210
  }
1211
+ if (componentSourceHash(component, identity) === componentSourceHash(remote, identity))
1212
+ await verifyComponentRuntime(client, remote);
1209
1213
  const typeTransitionBlocker = componentTypeTransitionBlocker(component, remote);
1210
1214
  if (typeTransitionBlocker) {
1211
1215
  throw new Error(`Cannot push ${targetPath}: ${typeTransitionBlocker}`);
@@ -1365,6 +1369,7 @@ async function pushSingleComponent(context, manifestPath, remoteCatalog) {
1365
1369
  });
1366
1370
  throw new Error(`Cannot push ${targetPath}: updated component did not verify against local source. Diagnostic: ${logPath}`);
1367
1371
  }
1372
+ await verifyComponentRuntime(client, refreshedRemote, 120_000);
1368
1373
  upsertLockFromRemote(context, refreshedRemote, targetPath, component, context.componentEnvironment);
1369
1374
  if (!configurationChanged && !elementsChanged) {
1370
1375
  const result = {
@@ -1681,6 +1686,18 @@ export async function buildComponentPlan(context, scope = { enabled: false, base
1681
1686
  ...(scope.enabled ? { inScope } : {}),
1682
1687
  };
1683
1688
  });
1689
+ for (const item of items) {
1690
+ if (item.componentType !== 'CUSTOM_NODEJS' || item.status !== 'clean' || !item.remoteComponentId)
1691
+ continue;
1692
+ try {
1693
+ await verifyComponentRuntime(context.client, remoteCatalog.byIdentity.get(item.identityKey || item.componentId)?.component || { type: 'CUSTOM_NODEJS', componentId: item.remoteComponentId });
1694
+ }
1695
+ catch (error) {
1696
+ item.status = 'blocked';
1697
+ item.blocked = true;
1698
+ item.reason = error instanceof Error ? error.message : String(error);
1699
+ }
1700
+ }
1684
1701
  const scopedItems = (scope.enabled ? items.filter((item) => item.inScope) : items)
1685
1702
  .sort((left, right) => (componentDeploymentRank(left.componentType) - componentDeploymentRank(right.componentType)
1686
1703
  || String(left.identityKey || left.componentId).localeCompare(String(right.identityKey || right.componentId))));
@@ -51,7 +51,7 @@ function printPlanText(context, plan) {
51
51
  const { println } = context;
52
52
  println(`Comparing ${paint(plan.from.env, ANSI.bold + ANSI.cyan)} -> ${paint(plan.to.env, ANSI.bold + ANSI.cyan)}`);
53
53
  for (const item of plan.items) {
54
- if (item.action === 'noop') {
54
+ if (item.action === 'noop' && !item.blocked) {
55
55
  continue;
56
56
  }
57
57
  const mark = ACTION_MARKS[item.action];
@@ -60,7 +60,7 @@ function printPlanText(context, plan) {
60
60
  : item.reason
61
61
  ? ` (${item.reason})`
62
62
  : '';
63
- const line = `${mark.symbol} ${item.action.padEnd(9)} ${item.resourceType} ${item.stableKey}${detail}`;
63
+ const line = `${item.blocked ? '!' : mark.symbol} ${(item.blocked ? 'blocked' : item.action).padEnd(9)} ${item.resourceType} ${item.stableKey}${detail}`;
64
64
  println(paint(line, mark.code));
65
65
  }
66
66
  const { counts } = plan;
@@ -68,7 +68,7 @@ function printPlanText(context, plan) {
68
68
  + `${counts.noop} unchanged, ${counts.orphan} orphaned, ${counts.collision} collisions.`);
69
69
  }
70
70
  function hasBlockingDrift(plan) {
71
- return plan.items.some((item) => item.action !== 'noop');
71
+ return plan.items.some((item) => item.action !== 'noop' || item.blocked);
72
72
  }
73
73
  function readScope(args) {
74
74
  const keys = readValues(args, ['key']);
@@ -298,6 +298,9 @@ async function handleEnvApply(context) {
298
298
  printPlanText(context, plan);
299
299
  }
300
300
  const changeCount = plan.counts.create + plan.counts.update + plan.counts.delete;
301
+ const blocked = plan.items.filter(item => item.blocked);
302
+ if (blocked.length)
303
+ throw new Error(`Cannot apply: ${blocked.length} component runtime(s) are not ready. ${blocked.map(item => item.reason).join(' ')}`);
301
304
  if (plan.counts.collision > 0) {
302
305
  throw new Error(`Cannot apply: ${plan.counts.collision} stable-key collision(s) in scope. Resolve duplicates or narrow the scope with --key/--category.`);
303
306
  }
@@ -342,8 +345,8 @@ async function handleEnvApply(context) {
342
345
  println(paint(`Warning: ${unverified.length} component(s) did not verify against the source after apply.`, ANSI.bold + ANSI.yellow));
343
346
  }
344
347
  }
345
- if (failed.length > 0) {
346
- throw new Error(`Apply finished with ${failed.length} failure(s).`);
348
+ if (failed.length > 0 || unverified.length > 0) {
349
+ throw new Error(`Apply finished with ${failed.length} failure(s), ${unverified.length} verification mismatch(es).`);
347
350
  }
348
351
  }
349
352
  export async function handleEnvCommand(context) {
@@ -364,6 +364,8 @@ function printMigrationPlan(context, plan) {
364
364
  }
365
365
  }
366
366
  function migrationItemActionLabel(item, legacyAction) {
367
+ if (item.status === 'activation-drift')
368
+ return item.status;
367
369
  return item.operation ?? (legacyAction === 'noop' ? item.status : legacyAction);
368
370
  }
369
371
  async function confirmRun(context, from, to) {
@@ -429,7 +431,9 @@ async function handleMigrationRead(context, input, command) {
429
431
  }
430
432
  if (command === 'plan' && input.sourceMode === 'workspace'
431
433
  && readBoolFlag(context.args, ['strict']) && plan.needsChanges) {
432
- throw new Error(`Deployment strict plan has pending changes: ${plan.operations.create} create, ${plan.operations.update} update${plan.prune ? `, ${plan.operations.delete || 0} delete` : ''}.`);
434
+ const eventActivationDrift = plan.events?.items.filter(item => item.status === 'activation-drift').length || 0;
435
+ const activationDrift = plan.schedules?.items.filter((item) => item.status === 'activation-drift').length || 0;
436
+ throw new Error(`Deployment strict plan has pending changes: ${plan.operations.create} create, ${plan.operations.update} update${activationDrift ? `, ${activationDrift} Schedule activation drift` : ''}${eventActivationDrift ? `, ${eventActivationDrift} Event activation drift` : ''}${plan.prune ? `, ${plan.operations.delete || 0} delete` : ''}.`);
433
437
  }
434
438
  if (command === 'verify' && plan.needsChanges) {
435
439
  throw new Error('Migration verification failed: target still requires changes.');
@@ -39,17 +39,19 @@ export async function handleSchedulesCommand(context) {
39
39
  let activation;
40
40
  if (activate) {
41
41
  const candidateCount = pushed.verifiedActivationCandidates.length;
42
- const confirmed = !isInteractiveTerminal() || await promptConfirm(`Activate ${candidateCount} verified Schedule(s) on "${displayName}"?`, false);
43
- if (confirmed) {
44
- const activationResults = await activateVerifiedSchedules({
45
- client,
46
- candidates: pushed.verifiedActivationCandidates,
47
- });
48
- results.push(...activationResults);
49
- activation = { candidateCount, results: activationResults };
42
+ if (pushed.results.some((item) => item.status === 'failed')) {
43
+ activation = { candidateCount, results: [], skipped: 'configuration phase has failures' };
50
44
  }
51
45
  else {
52
- activation = { candidateCount, results: [], skipped: 'activation not confirmed' };
46
+ const confirmed = !isInteractiveTerminal() || await promptConfirm(`Align activation for ${candidateCount} verified Schedule(s) on "${displayName}"?`, false);
47
+ if (confirmed) {
48
+ const activationResults = await activateVerifiedSchedules({ client, candidates: pushed.verifiedActivationCandidates });
49
+ results.push(...activationResults);
50
+ activation = { candidateCount, results: activationResults };
51
+ }
52
+ else {
53
+ activation = { candidateCount, results: [], skipped: 'activation not confirmed' };
54
+ }
53
55
  }
54
56
  }
55
57
  if (readBoolFlag(context.args, ['json'])) {
@@ -0,0 +1,8 @@
1
+ import type { RevoClient } from './client.ts';
2
+ import type { ComponentRecord } from './types.ts';
3
+ export declare function isComponentDigest(value: unknown): value is string;
4
+ /** Canonical API content identity, separate from portable configuration hashes. */
5
+ export declare function componentContentDigest(component: ComponentRecord): string;
6
+ export declare function componentRevisionByDigest(client: RevoClient, componentId: string, digest: string): Promise<ComponentRecord>;
7
+ export declare function componentRuntimeBlocker(runtime: unknown, active?: boolean): string | null;
8
+ export declare function verifyComponentRuntime(client: RevoClient, component: ComponentRecord, waitMs?: number): Promise<void>;
@@ -0,0 +1,68 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { setTimeout as delay } from 'node:timers/promises';
3
+ import { hashPortableComponentSource } from "./component-lock.js";
4
+ import { unwrapData, isRecord } from "./resource-syncs/util.js";
5
+ export function isComponentDigest(value) {
6
+ return typeof value === 'string' && /^v1:sha256:[a-f0-9]{64}$/.test(value);
7
+ }
8
+ /** Canonical API content identity, separate from portable configuration hashes. */
9
+ export function componentContentDigest(component) {
10
+ const digest = (value) => `v1:sha256:${createHash('sha256').update(value).digest('hex')}`;
11
+ const type = String(component.type || '');
12
+ const elements = [...(component.elements || [])]
13
+ .sort((a, b) => Number(a.order) - Number(b.order) || String(a.key).localeCompare(String(b.key)))
14
+ .map(element => [element.key, Number(element.order), Boolean(element.hidden),
15
+ digest(typeof element.details === 'string' ? element.details : '')]);
16
+ return digest(JSON.stringify([1, type, type.endsWith('_LIB') ? component.name || '' : null, elements]));
17
+ }
18
+ export async function componentRevisionByDigest(client, componentId, digest) {
19
+ if (!isComponentDigest(digest))
20
+ throw new Error('Expected canonical v1 component digest.');
21
+ const current = unwrapData(await client.getComponent(componentId));
22
+ if (!current || current.active === false || current.deletedAt || current.deletedBy)
23
+ throw new Error('Pinned component is missing or deleted.');
24
+ if (componentContentDigest(current) === digest)
25
+ return current;
26
+ const matches = await client.resolveComponentDigest(digest);
27
+ const rows = matches.filter(row => row.componentId === componentId && row.digest === digest && Number.isInteger(row.version));
28
+ if (!rows.length)
29
+ throw new Error(`Component digest ${digest} does not exist for the target component.`);
30
+ const revision = rows.sort((a, b) => b.version - a.version)[0];
31
+ const snapshot = unwrapData(await client.getComponentSnapshotVersion(componentId, revision.version));
32
+ if (!snapshot || componentContentDigest(snapshot) !== digest)
33
+ throw new Error('Component digest readback differs from the selected revision.');
34
+ return snapshot;
35
+ }
36
+ export function componentRuntimeBlocker(runtime, active = true) {
37
+ const value = unwrapData(runtime);
38
+ if (!isRecord(value) || value.availability !== (active ? 'READY' : 'DISABLED') || value.hasPendingRevision !== false
39
+ || !value.activeRevisionId || value.activeRevisionId !== value.desiredRevisionId) {
40
+ return `Custom component runtime is not converged: availability=${String(value?.availability)}, activationMode=${String(value?.activationMode)}, pending=${String(value?.hasPendingRevision)}.`;
41
+ }
42
+ return null;
43
+ }
44
+ export async function verifyComponentRuntime(client, component, waitMs = 0) {
45
+ if (component.type !== 'CUSTOM_NODEJS')
46
+ return;
47
+ const id = String(component.componentId || component.id || '');
48
+ if (!id)
49
+ throw new Error('Custom component runtime requires its target component id.');
50
+ const deadline = Date.now() + waitMs;
51
+ while (true) {
52
+ const runtime = unwrapData(await client.getComponentRuntime(id));
53
+ const blocker = componentRuntimeBlocker(runtime, component.active !== false);
54
+ if (!blocker) {
55
+ if (waitMs > 0) {
56
+ const current = unwrapData(await client.getComponent(id));
57
+ if (hashPortableComponentSource(current) !== hashPortableComponentSource(component))
58
+ throw new Error('Custom component source changed while waiting for deployment.');
59
+ }
60
+ return;
61
+ }
62
+ const deployment = isRecord(runtime?.latestDeployment) ? runtime.latestDeployment : {};
63
+ if (Date.now() >= deadline || runtime?.activationMode === 'MANUAL' || deployment.status === 'FAILED') {
64
+ throw new Error(blocker + ' Review runtime deployment/activation and rerun; saved source alone is not a successful deployment.');
65
+ }
66
+ await delay(Math.min(1000, Math.max(1, deadline - Date.now())));
67
+ }
68
+ }
@@ -138,6 +138,7 @@ export declare function normalizeComponentSource(component: ComponentRecord): {
138
138
  active: boolean;
139
139
  type: string;
140
140
  async: boolean;
141
+ metadata: Record<string, unknown>;
141
142
  elements: {
142
143
  key: string;
143
144
  desc: string | null;
@@ -154,6 +155,7 @@ export declare function normalizePortableComponentSource(component: ComponentRec
154
155
  active: boolean;
155
156
  type: string;
156
157
  async: boolean;
158
+ metadata: Record<string, unknown>;
157
159
  elements: {
158
160
  key: string;
159
161
  desc: string | null;
@@ -163,10 +165,10 @@ export declare function normalizePortableComponentSource(component: ComponentRec
163
165
  }[];
164
166
  };
165
167
  export declare function hashPortableComponentSource(component: ComponentRecord): string;
166
- export declare const PORTABLE_COMPONENT_CONFIG_FIELDS: readonly ["name", "category", "desc", "active", "type", "async"];
168
+ export declare const PORTABLE_COMPONENT_CONFIG_FIELDS: readonly ["name", "category", "desc", "active", "type", "async", "metadata"];
167
169
  export type PortableComponentConfigField = (typeof PORTABLE_COMPONENT_CONFIG_FIELDS)[number];
168
170
  export declare function diffPortableComponentSource(source: ComponentRecord, target: ComponentRecord): {
169
- configurationFields: ("desc" | "name" | "category" | "type" | "active" | "async")[];
171
+ configurationFields: ("metadata" | "desc" | "name" | "category" | "type" | "active" | "async")[];
170
172
  elementsChanged: boolean;
171
173
  changedFields: string[];
172
174
  };
@@ -2,7 +2,7 @@ import crypto from 'node:crypto';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { REVO_PROJECT_DIR } from "./project.js";
5
- import { COMPONENT_IDENTITY_BY_ID, normalizeComponentIdentityConfig, readComponentIdentityValue, sameComponentIdentityConfig, } from "./resource-metadata.js";
5
+ import { COMPONENT_IDENTITY_BY_ID, normalizeComponentIdentityConfig, readComponentIdentityValue, sameComponentIdentityConfig, sanitizeUserMetadata, } from "./resource-metadata.js";
6
6
  import { readJsonFile, writeJsonFile } from "./utils.js";
7
7
  export const REVO_LOCK_FILE = path.join(REVO_PROJECT_DIR, 'revo.lock.json');
8
8
  const VOLATILE_COMPONENT_FIELDS = new Set([
@@ -84,6 +84,7 @@ export function normalizeComponentSource(component) {
84
84
  active: source.active ?? true,
85
85
  type: source.type || '',
86
86
  async: Boolean(source.async),
87
+ metadata: sanitizeUserMetadata(source.metadata),
87
88
  elements: [...(source.elements || [])]
88
89
  .map((element) => ({
89
90
  key: typeof element.key === 'string' ? element.key : '',
@@ -115,11 +116,12 @@ export const PORTABLE_COMPONENT_CONFIG_FIELDS = [
115
116
  'active',
116
117
  'type',
117
118
  'async',
119
+ 'metadata',
118
120
  ];
119
121
  export function diffPortableComponentSource(source, target) {
120
122
  const sourcePortable = normalizePortableComponentSource(source);
121
123
  const targetPortable = normalizePortableComponentSource(target);
122
- const configurationFields = PORTABLE_COMPONENT_CONFIG_FIELDS.filter((field) => sourcePortable[field] !== targetPortable[field]);
124
+ const configurationFields = PORTABLE_COMPONENT_CONFIG_FIELDS.filter((field) => hashStable(sourcePortable[field]) !== hashStable(targetPortable[field]));
123
125
  const elementsChanged = hashStable(sourcePortable.elements) !== hashStable(targetPortable.elements);
124
126
  return {
125
127
  configurationFields,
@@ -0,0 +1,14 @@
1
+ export type DatabaseIndex = {
2
+ columns: Array<string | Record<string, unknown>>;
3
+ name?: string;
4
+ using?: string;
5
+ unique?: boolean;
6
+ where?: Record<string, unknown>;
7
+ include?: string[];
8
+ };
9
+ /** Preserve structured PostgreSQL semantics and normalize only confirmed defaults. */
10
+ export declare function normalizeDatabaseIndexes(value: unknown): DatabaseIndex[];
11
+ export declare function databaseIndexPayload(value: unknown): Array<DatabaseIndex & {
12
+ columns: Record<string, unknown>[];
13
+ }>;
14
+ export declare function databaseIndexReferences(index: DatabaseIndex): string[];
@@ -0,0 +1,124 @@
1
+ import { hashStable } from "./component-lock.js";
2
+ import { isRecord } from "./resource-syncs/util.js";
3
+ function keys(value, allowed) {
4
+ if (Object.keys(value).some(key => !allowed.includes(key)))
5
+ throw new Error('Unsupported index field; refusing to discard it.');
6
+ }
7
+ function expression(value, depth = 0) {
8
+ if (!isRecord(value) || depth > 16)
9
+ throw new Error('Invalid index expression.');
10
+ keys(value, ['column', 'fn', 'args', 'cast', 'literal']);
11
+ for (const field of ['column', 'fn', 'cast'])
12
+ if (value[field] !== undefined && typeof value[field] !== 'string')
13
+ throw new Error('Invalid index expression field.');
14
+ if (value.args !== undefined) {
15
+ if (!Array.isArray(value.args))
16
+ throw new Error('Invalid index expression arguments.');
17
+ value.args.forEach(child => expression(child, depth + 1));
18
+ }
19
+ }
20
+ function predicate(value, depth = 0) {
21
+ if (!isRecord(value) || depth > 16)
22
+ throw new Error('Invalid index predicate.');
23
+ keys(value, ['and', 'or', 'not', 'column', 'op', 'value', 'values']);
24
+ for (const field of ['and', 'or'])
25
+ if (value[field] !== undefined) {
26
+ if (!Array.isArray(value[field]) || !value[field].length)
27
+ throw new Error('Invalid index predicate group.');
28
+ value[field].forEach(child => predicate(child, depth + 1));
29
+ }
30
+ if (value.not !== undefined)
31
+ predicate(value.not, depth + 1);
32
+ if (value.column !== undefined && typeof value.column !== 'string')
33
+ throw new Error('Invalid index predicate column.');
34
+ if (value.op !== undefined && !['eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'like', 'ilike', 'in', 'between', 'isnull', 'notnull'].includes(String(value.op)))
35
+ throw new Error('Invalid index predicate operator.');
36
+ if (value.values !== undefined && !Array.isArray(value.values))
37
+ throw new Error('Invalid index predicate values.');
38
+ }
39
+ /** Preserve structured PostgreSQL semantics and normalize only confirmed defaults. */
40
+ export function normalizeDatabaseIndexes(value) {
41
+ if (value == null)
42
+ return [];
43
+ if (!Array.isArray(value))
44
+ throw new Error('indexes must be an array.');
45
+ return value.map((raw, position) => {
46
+ if (!isRecord(raw))
47
+ throw new Error('Invalid index.');
48
+ keys(raw, ['name', 'using', 'columns', 'where', 'include', 'unique']);
49
+ if (!Array.isArray(raw.columns) || !raw.columns.length)
50
+ throw new Error('Index requires columns.');
51
+ if (raw.name !== undefined && (typeof raw.name !== 'string' || !raw.name.trim()))
52
+ throw new Error('Invalid index name.');
53
+ if (raw.using !== undefined && !['btree', 'hash', 'gist', 'spgist', 'gin', 'brin'].includes(String(raw.using)))
54
+ throw new Error('Invalid index method.');
55
+ if (raw.unique !== undefined && typeof raw.unique !== 'boolean')
56
+ throw new Error('Invalid index unique flag.');
57
+ if (raw.include !== undefined && (!Array.isArray(raw.include) || !raw.include.every(c => typeof c === 'string' && c.trim())))
58
+ throw new Error('Invalid index include columns.');
59
+ if (raw.where !== undefined)
60
+ predicate(raw.where);
61
+ const columns = raw.columns.map(column => {
62
+ if (typeof column === 'string' && column.trim())
63
+ return column;
64
+ if (!isRecord(column))
65
+ throw new Error('Invalid index column.');
66
+ keys(column, ['name', 'expression', 'order', 'nulls', 'collation', 'opclass']);
67
+ if (column.name !== undefined && (typeof column.name !== 'string' || !column.name.trim()))
68
+ throw new Error('Invalid index column name.');
69
+ if (!column.name && !column.expression)
70
+ throw new Error('Index column requires name or expression.');
71
+ if (column.expression !== undefined)
72
+ expression(column.expression);
73
+ if (column.order !== undefined && !['ASC', 'DESC'].includes(String(column.order)))
74
+ throw new Error('Invalid index order.');
75
+ if (column.nulls !== undefined && !['FIRST', 'LAST'].includes(String(column.nulls)))
76
+ throw new Error('Invalid index null placement.');
77
+ for (const field of ['collation', 'opclass'])
78
+ if (column[field] !== undefined && typeof column[field] !== 'string')
79
+ throw new Error('Invalid index column field.');
80
+ const normalized = structuredClone(column);
81
+ if (normalized.nulls === (normalized.order === 'DESC' ? 'FIRST' : 'LAST'))
82
+ delete normalized.nulls;
83
+ if (normalized.order === 'ASC')
84
+ delete normalized.order;
85
+ return Object.keys(normalized).length === 1 && typeof normalized.name === 'string' ? normalized.name : normalized;
86
+ });
87
+ return {
88
+ columns,
89
+ name: raw.name || `index_${position + 1}`,
90
+ ...(raw.using && raw.using !== 'btree' ? { using: raw.using } : {}),
91
+ ...(raw.unique === true ? { unique: true } : {}),
92
+ ...(raw.where !== undefined ? { where: structuredClone(raw.where) } : {}),
93
+ ...(Array.isArray(raw.include) && raw.include.length ? { include: [...raw.include] } : {}),
94
+ };
95
+ }).sort((a, b) => hashStable(a).localeCompare(hashStable(b)));
96
+ }
97
+ export function databaseIndexPayload(value) {
98
+ return normalizeDatabaseIndexes(value).map(index => ({ ...index, columns: index.columns.map(c => typeof c === 'string' ? { name: c } : c) }));
99
+ }
100
+ export function databaseIndexReferences(index) {
101
+ const refs = [...(index.include || [])];
102
+ const visit = (value) => {
103
+ if (!isRecord(value))
104
+ return;
105
+ if (typeof value.column === 'string')
106
+ refs.push(value.column);
107
+ for (const field of ['args', 'and', 'or'])
108
+ if (Array.isArray(value[field]))
109
+ value[field].forEach(visit);
110
+ if (value.not)
111
+ visit(value.not);
112
+ };
113
+ index.columns.forEach(c => {
114
+ if (typeof c === 'string')
115
+ refs.push(c);
116
+ else {
117
+ if (typeof c.name === 'string')
118
+ refs.push(c.name);
119
+ visit(c.expression);
120
+ }
121
+ });
122
+ visit(index.where);
123
+ return refs;
124
+ }
@@ -13,6 +13,7 @@ export type EnvComponentEntry = {
13
13
  component: ComponentRecord;
14
14
  portable: PortableComponentSource;
15
15
  portableHash: string;
16
+ runtimeBlocker?: string;
16
17
  };
17
18
  export type EnvCollision = {
18
19
  stableKey: string;
@@ -37,6 +38,7 @@ export type EnvSyncPlanItem = {
37
38
  targetComponentId: string | null;
38
39
  sourceHash: string | null;
39
40
  targetHash: string | null;
41
+ blocked?: boolean;
40
42
  changedFields?: string[];
41
43
  addedElementKeys?: string[];
42
44
  removedElementKeys?: string[];