@revoengine/cli 1.0.16 → 1.0.17

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
@@ -8,6 +8,10 @@ The CLI has three main capabilities:
8
8
  2. **Project migration** — plan, run, and verify a direct migration between two saved projects with `--from` and `--to`.
9
9
  3. **Resource synchronization** — work with one supported resource family through its dedicated `pull`, `plan`, and `push` commands.
10
10
 
11
+ ## Version 1.0.17
12
+
13
+ Repository deployment can now reconcile all tracked Stable Key definitions with `plan/deploy --prune`, review exact deletions and reuse a saved plan in CI. Retained dependencies are updated before obsolete definitions are deleted. Ordinary planner metadata is printed on one line per item; changes and diffs retain their detailed formatting. See the repository workflow below for approval, scope and failure behavior.
14
+
11
15
  ## Requirements and installation
12
16
 
13
17
  - Node.js 24 or newer
@@ -295,9 +299,27 @@ revo deploy --yes --json
295
299
 
296
300
  Repository deployment uses desired-source-wins upsert: it can adopt a missing baseline or overwrite target content drift with the repository state. Its Database Table policy permits supported table renames, column additions and changes, and copying foreign-reference declarations as metadata. Copying those declarations does not create physical SQL foreign-key constraints.
297
301
 
298
- `deploy --force` additionally approves supported high-impact operations reported by `plan`, including column removal, managed partition deletion, Materialized View Schedule writes, Schedule target-type changes, and Group or Role Group writes. Review them with `revo plan --force` before deployment. Force does not bypass invalid identity, missing dependencies, unsupported DDL, ambiguity, or failed verification. Root-table orphan deletion is available only through the dedicated table push.
302
+ `deploy --force` additionally approves supported high-impact operations reported by `plan`, including column removal, managed partition deletion, Materialized View Schedule writes, Schedule target-type changes, and Group or Role Group writes. Review them with `revo plan --force` before deployment. Force does not bypass invalid identity, missing dependencies, unsupported DDL, ambiguity, or failed verification. Full repository reconciliation explicitly selects these supported operations with `--prune`; it does not require `--force`.
303
+
304
+ To reconcile all tracked families, review the complete plan and approve its deletion list:
305
+
306
+ ```bash
307
+ revo plan --prune --out reviewed-plan.json
308
+ revo deploy --prune --reviewed-plan reviewed-plan.json
309
+ # CI: approval is supplied by the pipeline's confirmation policy
310
+ revo deploy --prune --yes --reviewed-plan reviewed-plan.json
311
+ revo version --json
312
+ ```
313
+
314
+ `--prune` makes local manifests authoritative for the configured `trackedResources`. A keyed target resource absent locally is a deletion candidate even without an old lock entry. Unkeyed resources are unmanaged and preserved. This covers Components, Job Templates, Endpoints, Events, Schedules, Database Tables (including partitions), Database Views, Groups, Role Groups and Service Accounts when selected. Runtime Job executions/history and Webhook deliveries are outside this definition-sync scope; their existing lifecycle is unaffected. Choose only resource families owned by the repository: an empty selected family intentionally means deleting all its managed target definitions. Environment-local Service Accounts should be excluded from `trackedResources`.
315
+
316
+ The planner lists exact target IDs, names and Stable Keys in deletion order. Duplicate identity, retained local/unmanaged/out-of-scope consumers, system resources and deletion of the authenticated Service Account block the plan. Upserts and their readback verification run first, allowing a retained Job Template or Endpoint to move to a replacement Component. Pruning then removes obsolete consumers before dependencies. API errors or failed readback stop further deletes. The owning APIs retain their existing permission and reference guards and soft-delete semantics, including the table subtree lifecycle and view automation deactivation. Root deletion is blocked by any retained or unmanaged partition. No arbitrary implicit consumer cleanup is performed.
317
+
318
+ `plan --out <file>` saves the plan without mutation or lock changes. `deploy --reviewed-plan <file>` requires `--prune` and compares the saved deletion list, revisions, authenticated instance and tracked scope with the live plan before any write. Upserts are followed by another live prune plan comparison. Each deletion rechecks identity and definition, verifies disappearance from the active catalog and clears only the selected target baseline; verified partition deletion retains its lock tombstone. Cascading table/view operations additionally recheck the remaining dependency graph. Plans are advisory, not an atomic server-side transaction: concurrent edits can still cause API rejection or partial progress. A fresh plan is required after target drift or a failed partial deployment.
319
+
320
+ `deploy` always shows the plan before interactive confirmation; `--yes` supplies noninteractive approval. Ordinary resource rows, field names, dependency hints and metadata use one line per item. Field/value diffs, list changes and code/SQL diffs retain multiline Git-style formatting. `revo version --json` advertises `workspacePrune` and `reviewedPrunePlan` so CI can reject older releases that ignore unknown flags. Without `--prune`, repository deployment remains upsert-only.
299
321
 
300
- To remove target Components that no longer have local manifests, review `revo component plan --all --prune` and run `revo component push --all --prune --yes --force`. Prune matches target Components by the configured identity (Stable Key when enabled), even when their instance UUID or content differs from an old lock baseline. Components without that identity remain unmanaged. Before deletion, the CLI rechecks that no local manifest appeared and that the live target still matches the freshly computed plan; it verifies removal from the active catalog before clearing any selected lock baseline. `component plan --all --strict` reports drift but never deletes resources.
322
+ Component-only reconciliation remains available through `revo component plan --all --prune` and `revo component push --all --prune --yes`; interactive confirmation is also supported. This matches the configured identity, rechecks local reappearance and live target drift, verifies deletion and clears only the selected environment baseline. `--force` is not required for explicit Component pruning. Named `migrate` and legacy `env apply` retain their existing scope and confirmation rules; `migrate --prune` is rejected.
301
323
 
302
324
  ## 2. Project-to-project migration
303
325
 
@@ -448,7 +470,7 @@ Review `database-tables plan --all` before a destructive push. `database-tables
448
470
 
449
471
  `database-tables push --all --prune-partitions --yes --force` removes only previously managed partitions whose local manifests were removed. It deletes from leaves to root, refuses to remove a parent with an active child, and records a tombstone in the selected environment's lock after verified deletion. Unknown target-only partitions stay untouched. `database-tables push '<stableKey>' --prune-orphans --yes --force` can remove a target-only root with that Stable Key without a prior baseline. Before either remote deletion, the CLI rechecks live identity and dependencies; active child partitions or Database Views referencing the table block it. A successful delete is verified before the lock changes.
450
472
 
451
- `database-tables pull --prune-orphans --yes --force` removes local manifests missing from the source; it never deletes target tables. Dedicated plan reports root orphans without accepting `--prune-orphans`. Repository `deploy --force` can delete previously managed partitions but not root orphans. Named `migrate` does not prune remote tables or partitions.
473
+ `database-tables pull --prune-orphans --yes --force` removes local manifests missing from the source; it never deletes target tables. Dedicated plan reports root orphans without accepting `--prune-orphans`. Repository `deploy --force` retains its legacy partition-only removal policy; `deploy --prune` additionally reconciles all selected keyed table roots and partitions. Named `migrate` does not prune remote tables or partitions.
452
474
 
453
475
  Resource plans support `--json` for automation and generally support `--strict` as a convergence gate. Human-readable plans show changes by default and hide informational details such as dependency readiness, component hashes, owners, and size statistics; add `--hints` to show them in individual plans, `revo plan`, and `revo migrate plan`. JSON plans still include the complete diagnostic data. Run `revo --help` for resource-specific safety flags such as `--activate`, `--skip-partitions`, and prune controls.
454
476
 
package/dist/src/cli.js CHANGED
@@ -198,7 +198,7 @@ async function runMain(args, argv) {
198
198
  const command = args._[0];
199
199
  const noPositionals = args._.length === 0;
200
200
  if (command === 'version' || ((args.version !== undefined || args.V !== undefined) && noPositionals)) {
201
- print(packageVersion);
201
+ print(args.json ? { version: packageVersion, capabilities: { workspacePrune: true, reviewedPrunePlan: true } } : packageVersion);
202
202
  return;
203
203
  }
204
204
  if (command === 'info' || ((args.i === true || args.info === true) && noPositionals)) {
@@ -1,5 +1,6 @@
1
1
  import { RequestQueue } from './request-queue.ts';
2
2
  import type { ComponentRecord, DatabaseSchemaRecord, DatabaseViewRecord, EndpointRecord, EventRecord, GroupRecord, JobTemplateRecord, RoleGroupRecord, ServiceAccountRecord, ScheduleRecord } from './types.ts';
3
+ import type { TrackableResourceType } from './tracked-resources.ts';
3
4
  export type RequestOptions = {
4
5
  query?: Record<string, unknown>;
5
6
  body?: unknown;
@@ -404,9 +405,12 @@ export declare class RevoClient {
404
405
  createComponent(body: unknown): Promise<unknown>;
405
406
  updateComponent(componentId: string, body: unknown): Promise<unknown>;
406
407
  deleteComponent(componentId: string): Promise<ApiResponse<unknown>>;
408
+ deleteWorkspaceResource(resource: TrackableResourceType, id: string): Promise<unknown>;
407
409
  private accountForSync;
408
410
  getAccount(userId: string): Promise<ServiceAccountRecord>;
409
- listAllServiceAccounts(): Promise<{
411
+ listAllServiceAccounts(options?: {
412
+ includeHumans?: boolean;
413
+ }): Promise<{
410
414
  serviceAccounts: ServiceAccountRecord[];
411
415
  }>;
412
416
  getServiceAccount(userId: string): Promise<ServiceAccountRecord>;
@@ -1177,6 +1177,31 @@ export class RevoClient {
1177
1177
  spinnerLabel: 'Deleting component',
1178
1178
  });
1179
1179
  }
1180
+ async deleteWorkspaceResource(resource, id) {
1181
+ const encoded = encodeURIComponent(id);
1182
+ const single = {
1183
+ component: `/api/v1/component/${encoded}`,
1184
+ 'database-table': `/api/v1/databases/${encoded}`,
1185
+ group: `/api/v1/groups/${encoded}`,
1186
+ 'role-group': `/api/v1/role-groups/${encoded}`,
1187
+ 'service-account': `/api/v1/accounts/${encoded}`,
1188
+ };
1189
+ const bulk = {
1190
+ 'job-template': '/api/v1/automation/template/delete',
1191
+ schedule: '/api/v1/automation/schedule/delete',
1192
+ event: '/api/v1/automation/event/delete',
1193
+ endpoint: '/api/v1/endpoints/delete',
1194
+ 'database-view': '/api/v1/databases/views/delete',
1195
+ };
1196
+ const requestPath = single[resource] || bulk[resource];
1197
+ if (!requestPath)
1198
+ throw new Error(`Unsupported workspace deletion family: ${resource}.`);
1199
+ return this.requestData(single[resource] ? 'DELETE' : 'POST', requestPath, {
1200
+ ...(bulk[resource] ? { body: { data: [id] } } : {}),
1201
+ maxRetries: 0,
1202
+ spinnerLabel: `Deleting ${resource}`,
1203
+ });
1204
+ }
1180
1205
  accountForSync(value) {
1181
1206
  const wrapper = isRecord(value) && isRecord(value.data) ? value.data : value;
1182
1207
  if (!isRecord(wrapper)) {
@@ -1197,7 +1222,7 @@ export class RevoClient {
1197
1222
  async getAccount(userId) {
1198
1223
  return this.accountForSync(await this.requestData('GET', `/api/v1/accounts/${encodeURIComponent(userId)}`, { sensitiveAccountPayload: true }));
1199
1224
  }
1200
- async listAllServiceAccounts() {
1225
+ async listAllServiceAccounts(options = {}) {
1201
1226
  const serviceAccounts = [];
1202
1227
  let skip = 0;
1203
1228
  const seenIds = new Set();
@@ -1209,7 +1234,7 @@ export class RevoClient {
1209
1234
  }));
1210
1235
  for (const item of page.items) {
1211
1236
  const account = this.accountForSync(item);
1212
- if (account.serviceAccount === true && !account.deletedAt) {
1237
+ if ((account.serviceAccount === true || options.includeHumans === true) && !account.deletedAt) {
1213
1238
  if (!account.userId || seenIds.has(account.userId)) {
1214
1239
  throw new Error('Invalid or repeated account ID while listing service accounts.');
1215
1240
  }
@@ -1465,13 +1465,13 @@ export async function pushAllComponents(context, options) {
1465
1465
  migrateComponentLockIdentity(cwd, identity, buildLocalComponentCatalog(cwd, identity), remoteCatalog);
1466
1466
  }
1467
1467
  await assertNoComponentTypeTransitionBlockers(context, manifests, identity, remoteCatalog);
1468
- await confirmBulkAction(context, 'push', manifests.length + pruneCandidates.length, options.force || options.yes);
1469
1468
  if (pruneCandidates.length > 0) {
1470
1469
  printSyncNotice(println, `Pruning ${pruneCandidates.length} managed component(s) absent from the repository.`);
1471
1470
  for (const item of pruneCandidates) {
1472
1471
  println(` - ${item.identityKey || item.componentId} (${item.remoteComponentId})`);
1473
1472
  }
1474
1473
  }
1474
+ await confirmBulkAction(context, 'push', manifests.length + pruneCandidates.length, options.force || options.yes);
1475
1475
  const startedAt = Date.now();
1476
1476
  const results = [];
1477
1477
  for (const manifestPath of manifests) {
@@ -2047,9 +2047,6 @@ export async function handleComponentCommand(context) {
2047
2047
  if (prune && (!['plan', 'push'].includes(subcommand) || !all || changedScope.enabled)) {
2048
2048
  throw new Error('Component --prune requires plan --all or push --all without --changed.');
2049
2049
  }
2050
- if (prune && subcommand === 'push' && (!yes || !force)) {
2051
- throw new Error('Component push --prune requires --yes --force.');
2052
- }
2053
2050
  if (context.componentEnvironment && ['pull', 'plan', 'push'].includes(subcommand)) {
2054
2051
  const identity = resolveComponentIdentity(context);
2055
2052
  if (identity.mode !== 'stableKey') {
@@ -1,3 +1,7 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { normalizeStableKeyValue } from "../resource-metadata.js";
4
+ import { samePrunePlan } from "../workspace-prune.js";
1
5
  import { DEFAULT_ENV_NAME } from "../config.js";
2
6
  import { buildMigrationPlan, pullResourcesToWorkspace, runMigration, } from "../migration.js";
3
7
  import { isInteractiveTerminal, promptConfirm } from "../prompt.js";
@@ -100,13 +104,17 @@ function readMigrationInput(context) {
100
104
  allowDestructive: readBoolFlag(context.args, ['force', 'f']),
101
105
  };
102
106
  }
107
+ function retainedPlanItems(plan, resource, items) {
108
+ const removed = new Set(plan.prune?.items.filter((item) => item.resource === resource).map((item) => normalizeStableKeyValue(item.stableKey)));
109
+ return items.filter((item) => !item.stableKey || !removed.has(normalizeStableKeyValue(item.stableKey)));
110
+ }
103
111
  function printMigrationPlan(context, plan) {
104
112
  const phaseLabel = plan.from === 'workspace' ? 'Deployment plan' : 'Migration';
105
113
  context.println(`${phaseLabel} ${plan.from} -> ${plan.to}`);
106
114
  context.println(`Resources: ${plan.resources.join(' -> ')}.`);
107
115
  context.println(`Ready to ${plan.from === 'workspace' ? 'deploy' : 'migrate'}: ${plan.readyToMigrate ? 'yes' : 'no'}.`);
108
116
  context.println(`Changes required: ${plan.needsChanges ? 'yes' : 'no'}; verdict: ${plan.verdict}.`);
109
- context.println(`Summary: create ${plan.operations.create}, update ${plan.operations.update}, adopt ${plan.operations.adopt}, unchanged ${plan.operations.noop}, excluded ${plan.operations.excluded}, blocked ${plan.operations.blocked}.`);
117
+ context.println(`Summary: create ${plan.operations.create}, update ${plan.operations.update}${plan.prune ? `, delete ${plan.operations.delete || 0}` : ''}, adopt ${plan.operations.adopt}, unchanged ${plan.operations.noop}, excluded ${plan.operations.excluded}, blocked ${plan.operations.blocked}.`);
110
118
  context.println(`Diagnostics: ${plan.warnings.length} warning(s), ${plan.blockers.length} blocker(s).`);
111
119
  if (plan.sourcePull.mode === 'repository') {
112
120
  context.println('Source snapshot: repository workspace (no remote source pull).');
@@ -131,7 +139,7 @@ function printMigrationPlan(context, plan) {
131
139
  environment: plan.to,
132
140
  counts: phase.operations,
133
141
  showHints: readBoolFlag(context.args, ['hints']),
134
- items: plan.databaseSchemas.items.map((item) => ({
142
+ items: retainedPlanItems(plan, 'database-table', plan.databaseSchemas.items).map((item) => ({
135
143
  status: schemaItemActionLabel(item),
136
144
  target: item.stableKey || item.name,
137
145
  reason: item.reason,
@@ -149,7 +157,7 @@ function printMigrationPlan(context, plan) {
149
157
  environment: plan.to,
150
158
  counts: phase.operations,
151
159
  showHints: readBoolFlag(context.args, ['hints']),
152
- items: plan.databaseViews.items.map((item) => ({
160
+ items: retainedPlanItems(plan, 'database-view', plan.databaseViews.items).map((item) => ({
153
161
  status: viewItemActionLabel(item),
154
162
  target: item.stableKey || item.name,
155
163
  reason: item.reason,
@@ -173,7 +181,7 @@ function printMigrationPlan(context, plan) {
173
181
  environment: plan.to,
174
182
  counts: phase.operations,
175
183
  showHints: readBoolFlag(context.args, ['hints']),
176
- items: plan.components.items.map((item) => ({
184
+ items: retainedPlanItems(plan, 'component', plan.components.items).map((item) => ({
177
185
  status: componentItemActionLabel(item),
178
186
  target: item.stableKey || item.path,
179
187
  reason: item.reason,
@@ -192,7 +200,7 @@ function printMigrationPlan(context, plan) {
192
200
  }
193
201
  if (phase.resource === 'service-account' && plan.serviceAccounts) {
194
202
  printSyncPlan(context.println, { title: `${phaseLabel} phase ${phase.order} / Service Account`, environment: plan.to,
195
- counts: phase.operations, items: plan.serviceAccounts.items, warnings: phase.warnings, blockers: phase.blockers });
203
+ counts: phase.operations, items: retainedPlanItems(plan, 'service-account', plan.serviceAccounts.items), warnings: phase.warnings, blockers: phase.blockers });
196
204
  }
197
205
  if (phase.resource === 'job-template' && plan.jobTemplates) {
198
206
  printSyncPlan(context.println, {
@@ -200,7 +208,7 @@ function printMigrationPlan(context, plan) {
200
208
  environment: plan.to,
201
209
  counts: phase.operations,
202
210
  showHints: readBoolFlag(context.args, ['hints']),
203
- items: plan.jobTemplates.items.map((item) => ({
211
+ items: retainedPlanItems(plan, 'job-template', plan.jobTemplates.items).map((item) => ({
204
212
  status: jobTemplateItemActionLabel(item),
205
213
  target: item.stableKey || item.name,
206
214
  reason: item.reason,
@@ -221,7 +229,7 @@ function printMigrationPlan(context, plan) {
221
229
  environment: plan.to,
222
230
  counts: phase.operations,
223
231
  showHints: readBoolFlag(context.args, ['hints']),
224
- items: plan.endpoints.items.map((item) => ({
232
+ items: retainedPlanItems(plan, 'endpoint', plan.endpoints.items).map((item) => ({
225
233
  status: endpointItemActionLabel(item),
226
234
  target: item.stableKey || item.name,
227
235
  reason: item.reason,
@@ -248,7 +256,7 @@ function printMigrationPlan(context, plan) {
248
256
  environment: plan.to,
249
257
  counts: phase.operations,
250
258
  showHints: readBoolFlag(context.args, ['hints']),
251
- items: plan.schedules.items.map((item) => ({
259
+ items: retainedPlanItems(plan, 'schedule', plan.schedules.items).map((item) => ({
252
260
  status: scheduleItemActionLabel(item),
253
261
  target: item.stableKey || item.name,
254
262
  reason: item.reason,
@@ -266,7 +274,7 @@ function printMigrationPlan(context, plan) {
266
274
  environment: plan.to,
267
275
  counts: phase.operations,
268
276
  showHints: readBoolFlag(context.args, ['hints']),
269
- items: plan.events.items.map((item) => ({
277
+ items: retainedPlanItems(plan, 'event', plan.events.items).map((item) => ({
270
278
  status: eventItemActionLabel(item),
271
279
  target: item.stableKey || item.name,
272
280
  reason: item.reason,
@@ -286,7 +294,7 @@ function printMigrationPlan(context, plan) {
286
294
  environment: plan.to,
287
295
  counts: phase.operations,
288
296
  showHints: readBoolFlag(context.args, ['hints']),
289
- items: plan.groups.items.map((item) => ({
297
+ items: retainedPlanItems(plan, 'group', plan.groups.items).map((item) => ({
290
298
  status: groupItemActionLabel(item),
291
299
  target: item.stableKey || item.name,
292
300
  reason: item.reason,
@@ -306,7 +314,7 @@ function printMigrationPlan(context, plan) {
306
314
  environment: plan.to,
307
315
  counts: phase.operations,
308
316
  showHints: readBoolFlag(context.args, ['hints']),
309
- items: plan.roleGroups.items.map((item) => ({
317
+ items: retainedPlanItems(plan, 'role-group', plan.roleGroups.items).map((item) => ({
310
318
  status: roleGroupItemActionLabel(item),
311
319
  target: item.stableKey || item.name,
312
320
  reason: item.reason,
@@ -319,6 +327,15 @@ function printMigrationPlan(context, plan) {
319
327
  });
320
328
  }
321
329
  }
330
+ if (plan.prune) {
331
+ printSyncPlan(context.println, {
332
+ title: 'Deletion after verified upserts', environment: plan.to,
333
+ counts: { delete: plan.prune.items.length },
334
+ items: plan.prune.items.map((item) => ({ status: 'delete', target: `${item.resource}:${item.stableKey}`,
335
+ details: [{ label: 'target', values: item.targetId }, { label: 'name', values: item.name }] })),
336
+ blockers: plan.prune.blockers,
337
+ });
338
+ }
322
339
  }
323
340
  function schemaItemActionLabel(item) {
324
341
  if (item.status === 'missing-lock') {
@@ -484,7 +501,8 @@ async function readWorkspaceDeploymentInput(context) {
484
501
  to: context.client.baseUrl,
485
502
  resources,
486
503
  withStats: readBoolFlag(context.args, ['with-stats']),
487
- allowDestructive: readBoolFlag(context.args, ['force', 'f']),
504
+ allowDestructive: readBoolFlag(context.args, ['force', 'f']) || readBoolFlag(context.args, ['prune']),
505
+ prune: readBoolFlag(context.args, ['prune']),
488
506
  sourceMode: 'workspace',
489
507
  targetClient: context.client,
490
508
  targetKey: `instance:${authenticatedInstance}`,
@@ -507,6 +525,12 @@ async function handleMigrationRead(context, input, command) {
507
525
  }
508
526
  return;
509
527
  }
528
+ const outputFile = readFlag(context.args, ['out']);
529
+ if (outputFile) {
530
+ if (command !== 'plan')
531
+ throw new Error('--out is supported by plan only.');
532
+ fs.writeFileSync(path.resolve(context.cwd, outputFile), `${JSON.stringify(plan, null, 2)}\n`, { mode: 0o600 });
533
+ }
510
534
  if (readBoolFlag(context.args, ['json'])) {
511
535
  context.print({ ...plan, command });
512
536
  }
@@ -519,13 +543,15 @@ async function handleMigrationRead(context, input, command) {
519
543
  }
520
544
  if (command === 'plan' && input.sourceMode === 'workspace'
521
545
  && readBoolFlag(context.args, ['strict']) && plan.needsChanges) {
522
- throw new Error(`Deployment strict plan has pending changes: ${plan.operations.create} create, ${plan.operations.update} update.`);
546
+ throw new Error(`Deployment strict plan has pending changes: ${plan.operations.create} create, ${plan.operations.update} update${plan.prune ? `, ${plan.operations.delete || 0} delete` : ''}.`);
523
547
  }
524
548
  if (command === 'verify' && plan.needsChanges) {
525
549
  throw new Error('Migration verification failed: target still requires changes.');
526
550
  }
527
551
  }
528
552
  export async function handleDiffCommand(context) {
553
+ if (readBoolFlag(context.args, ['prune']))
554
+ throw new Error('Review deletions with revo plan --prune; diff compares content only.');
529
555
  if (readBoolFlag(context.args, ['force', 'f'])) {
530
556
  throw new Error('Repository diff only compares content. Use revo plan --force to review force-gated deployment operations.');
531
557
  }
@@ -618,15 +644,16 @@ async function confirmDeploy(context) {
618
644
  if (readBoolFlag(context.args, ['yes', 'y'])) {
619
645
  return;
620
646
  }
621
- if (!isInteractiveTerminal() || !await promptConfirm(`Deploy the tracked workspace to "${context.client.baseUrl}"?`, false)) {
647
+ if (!isInteractiveTerminal() || !await promptConfirm(`Apply the displayed deployment plan to "${context.client.baseUrl}"${readBoolFlag(context.args, ['prune']) ? ', including all listed deletions' : ''}?`, false)) {
622
648
  throw new Error('Deployment requires confirmation. Re-run with --yes or use an interactive terminal.');
623
649
  }
624
650
  }
625
- function printRunResult(context, result) {
626
- printMigrationPlan(context, result.plan);
651
+ function printRunResult(context, result, showPlan = true) {
652
+ if (showPlan)
653
+ printMigrationPlan(context, result.plan);
627
654
  for (const item of result.results) {
628
655
  printSyncStatus(context.println, {
629
- status: item.status === 'deployed' ? 'Deployed' : item.status === 'write-unverified' ? 'Unverified' : item.status === 'failed' ? 'Failed' : 'Skipped',
656
+ status: item.status === 'deployed' ? 'Deployed' : item.status === 'pruned' ? 'Pruned' : item.status === 'write-unverified' ? 'Unverified' : item.status === 'failed' ? 'Failed' : 'Skipped',
630
657
  direction: 'push',
631
658
  targetPath: item.targetPath,
632
659
  reason: ('error' in item ? item.error : undefined) || item.reason,
@@ -635,14 +662,38 @@ function printRunResult(context, result) {
635
662
  context.println(`Final verdict: ${result.verdict}.`);
636
663
  }
637
664
  export async function handleDeployCommand(context) {
665
+ if (readBoolFlag(context.args, ['changed']) || readFlag(context.args, ['base']) || readValues(context.args, ['resources', 'resource']).length > 0) {
666
+ throw new Error('Repository deployment evaluates all tracked resources; select resources in .revoengine/revo.json.');
667
+ }
668
+ const input = { ...await readWorkspaceDeploymentInput(context), detailedDiff: true };
669
+ const preview = await buildMigrationPlan(input);
670
+ const reviewedFile = readFlag(context.args, ['reviewed-plan']);
671
+ if (reviewedFile) {
672
+ if (!input.prune)
673
+ throw new Error('--reviewed-plan requires --prune.');
674
+ const reviewed = JSON.parse(fs.readFileSync(path.resolve(context.cwd, reviewedFile), 'utf8'));
675
+ if (!reviewed.readyToMigrate || reviewed.schemaVersion !== 2 || reviewed.command !== 'plan'
676
+ || !reviewed.prune || !preview.prune || reviewed.pruneTargetKey !== preview.pruneTargetKey
677
+ || JSON.stringify(reviewed.resources) !== JSON.stringify(preview.resources)
678
+ || !samePrunePlan(reviewed.prune, preview.prune)) {
679
+ throw new Error('Reviewed deletion plan does not match this instance, resource scope or live target; run plan again.');
680
+ }
681
+ }
682
+ // Interactive confirmation must always expose the plan, including JSON mode.
683
+ if (!readBoolFlag(context.args, ['json']))
684
+ printMigrationPlan(context, preview);
685
+ else if (!readBoolFlag(context.args, ['yes', 'y']))
686
+ printMigrationPlan({ ...context, println: context.error }, preview);
687
+ if (!preview.readyToMigrate)
688
+ throw new Error(`Deployment plan is blocked by ${preview.blockers.length} issue(s).`);
638
689
  await confirmDeploy(context);
639
690
  const startedAt = Date.now();
640
- const result = await runMigration({ ...await readWorkspaceDeploymentInput(context), detailedDiff: true });
691
+ const result = await runMigration({ ...input, reviewedPrune: preview.prune });
641
692
  if (readBoolFlag(context.args, ['json'])) {
642
693
  context.print({ ...result, command: 'deploy' });
643
694
  }
644
695
  else {
645
- printRunResult(context, result);
696
+ printRunResult(context, result, false);
646
697
  printSyncSummary(context.println, 'Deployed', result.results, Date.now() - startedAt);
647
698
  }
648
699
  if (result.verdict !== 'succeeded') {
@@ -650,6 +701,8 @@ export async function handleDeployCommand(context) {
650
701
  }
651
702
  }
652
703
  export async function handleMigrateCommand(context) {
704
+ if (readBoolFlag(context.args, ['prune']))
705
+ throw new Error('Prune requires repository plan/deploy; named migration remains upsert-only.');
653
706
  const requestedSubcommand = context.args._[1] || 'plan';
654
707
  const dryRun = readBoolFlag(context.args, ['dry-run']);
655
708
  const subcommand = dryRun ? 'plan' : requestedSubcommand;
@@ -1,3 +1,4 @@
1
+ import { type WorkspacePrunePlan } from './workspace-prune.ts';
1
2
  import { type ServiceAccountsPlan, type ServiceAccountPullResult, type ServiceAccountPushResult } from './resource-syncs/service-account-sync.ts';
2
3
  import { RevoClient } from './client.ts';
3
4
  import { type ComponentPlan, type ComponentSyncResult } from './commands/component.ts';
@@ -11,7 +12,9 @@ import { type SchedulePullResult, type SchedulePushResult, type SchedulesPlan }
11
12
  import { type RoleGroupPullResult, type RoleGroupPushResult, type RoleGroupsPlan } from './resource-syncs/role-group-sync.ts';
12
13
  export type MigrationResource = 'database-table' | 'database-view' | 'component' | 'job-template' | 'endpoint' | 'schedule' | 'event' | 'group' | 'role-group' | 'service-account';
13
14
  export type MigrationVerdict = 'ready' | 'ready-with-warnings' | 'blocked';
14
- export type MigrationOperations = Record<'noop' | 'create' | 'update' | 'adopt' | 'excluded' | 'blocked', number>;
15
+ export type MigrationOperations = Record<'noop' | 'create' | 'update' | 'adopt' | 'excluded' | 'blocked', number> & {
16
+ delete?: number;
17
+ };
15
18
  type MigrationPushResult = DatabaseSchemaPushResult | DatabaseViewPushResult | ComponentSyncResult | JobTemplatePushResult | EndpointPushResult | SchedulePushResult | EventPushResult | GroupPushResult | RoleGroupPushResult | ServiceAccountPushResult;
16
19
  export type MigrationPhasePlan = {
17
20
  order: number;
@@ -40,8 +43,10 @@ export type MigrationPlan = {
40
43
  from: string;
41
44
  to: string;
42
45
  resources: MigrationResource[];
46
+ prune?: WorkspacePrunePlan;
47
+ pruneTargetKey?: string;
43
48
  policy: DatabaseSchemaMigrationPolicy & {
44
- mode: 'upsert';
49
+ mode: 'upsert' | 'reconcile';
45
50
  };
46
51
  needsChanges: boolean;
47
52
  readyToMigrate: boolean;
@@ -73,7 +78,7 @@ export type MigrationRun = {
73
78
  to: string;
74
79
  resources: MigrationResource[];
75
80
  policy: DatabaseSchemaMigrationPolicy & {
76
- mode: 'upsert';
81
+ mode: 'upsert' | 'reconcile';
77
82
  };
78
83
  verdict: 'succeeded' | 'blocked' | 'failed';
79
84
  sourcePull: {
@@ -101,6 +106,8 @@ type MigrationInputBase = {
101
106
  withStats?: boolean;
102
107
  allowDestructive?: boolean;
103
108
  detailedDiff?: boolean;
109
+ prune?: boolean;
110
+ reviewedPrune?: WorkspacePrunePlan;
104
111
  };
105
112
  export type MigrationInput = MigrationInputBase & ({
106
113
  sourceMode: 'workspace';
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import { applyWorkspacePrune, buildWorkspacePrunePlan, samePrunePlan } from "./workspace-prune.js";
2
3
  import { planIdentityMigration } from "./resource-syncs/identity-migration.js";
3
4
  import { SERVICE_ACCOUNTS_DIRECTORY, buildServiceAccountsPlan, pullServiceAccountsToWorkspace, pushServiceAccounts } from "./resource-syncs/service-account-sync.js";
4
5
  import os from 'node:os';
@@ -617,7 +618,7 @@ function applyWorkspaceDeploymentPolicy(input, phase, plans) {
617
618
  }
618
619
  const gates = [];
619
620
  const forceOperations = [];
620
- if (phase.resource === 'database-table' && plans.databaseSchemas) {
621
+ if (phase.resource === 'database-table' && plans.databaseSchemas && !input.prune) {
621
622
  for (const item of plans.databaseSchemas.items.filter((candidate) => candidate.status === 'delete-partition')) {
622
623
  const operation = {
623
624
  from: 'excluded',
@@ -677,7 +678,7 @@ function applyWorkspaceDeploymentPolicy(input, phase, plans) {
677
678
  const operations = { ...phase.operations };
678
679
  if (input.allowDestructive === true) {
679
680
  for (const operation of forceOperations) {
680
- operations[operation.from] = Math.max(0, operations[operation.from] - 1);
681
+ operations[operation.from] = Math.max(0, (operations[operation.from] || 0) - 1);
681
682
  operations.update += 1;
682
683
  }
683
684
  return {
@@ -690,7 +691,7 @@ function applyWorkspaceDeploymentPolicy(input, phase, plans) {
690
691
  return phase;
691
692
  }
692
693
  for (const gate of gates) {
693
- operations[gate.from] = Math.max(0, operations[gate.from] - 1);
694
+ operations[gate.from] = Math.max(0, (operations[gate.from] || 0) - 1);
694
695
  operations.blocked += 1;
695
696
  }
696
697
  const blockers = [...new Set([...phase.blockers, ...gates.map((gate) => gate.message)])];
@@ -795,7 +796,7 @@ function combinePlan(input) {
795
796
  const operations = emptyOperations();
796
797
  for (const phase of phases) {
797
798
  for (const key of Object.keys(operations)) {
798
- operations[key] += phase.operations[key];
799
+ operations[key] = (operations[key] || 0) + (phase.operations[key] || 0);
799
800
  }
800
801
  }
801
802
  const warnings = [...new Set(phases.flatMap((phase) => phase.warnings))];
@@ -1269,6 +1270,24 @@ async function planWorkspace(input) {
1269
1270
  if (identities) {
1270
1271
  combined.identityOrder = identities.ordered.map(({ resource, stableKey }) => ({ resource, stableKey }));
1271
1272
  }
1273
+ if (input.prune) {
1274
+ if (input.sourceMode !== 'workspace')
1275
+ throw new Error('Prune requires repository plan/deploy; named migration remains upsert-only.');
1276
+ combined.prune = await buildWorkspacePrunePlan({ cwd: input.cwd, client, resources });
1277
+ combined.pruneTargetKey = environmentKey;
1278
+ combined.policy.mode = 'reconcile';
1279
+ combined.operations.delete = combined.prune.items.length;
1280
+ combined.operations.blocked += combined.prune.blockers.length;
1281
+ for (const phase of combined.phases) {
1282
+ const removed = Math.min(phase.operations.excluded, combined.prune.items.filter((item) => item.resource === phase.resource).length);
1283
+ phase.operations.excluded -= removed;
1284
+ combined.operations.excluded -= removed;
1285
+ }
1286
+ combined.blockers = [...new Set([...combined.blockers, ...combined.prune.blockers])];
1287
+ combined.readyToMigrate = combined.blockers.length === 0;
1288
+ combined.needsChanges ||= combined.prune.items.length > 0;
1289
+ combined.verdict = phaseVerdict(combined.blockers, combined.warnings);
1290
+ }
1272
1291
  return combined;
1273
1292
  }
1274
1293
  export async function buildMigrationPlan(input) {
@@ -1298,7 +1317,7 @@ export async function buildMigrationPlan(input) {
1298
1317
  }
1299
1318
  }
1300
1319
  function resultsAreComplete(results) {
1301
- return results.every((result) => result.status === 'deployed' || result.status === 'skipped');
1320
+ return results.every((result) => result.status === 'deployed' || result.status === 'skipped' || result.status === 'pruned');
1302
1321
  }
1303
1322
  function componentResultsAreComplete(results) {
1304
1323
  return results.every((result) => result.status === 'deployed' || result.status === 'skipped');
@@ -1330,6 +1349,11 @@ export async function runMigration(input) {
1330
1349
  sourcePullMode,
1331
1350
  projectDependencies: true,
1332
1351
  });
1352
+ if (input.reviewedPrune && (!initialPlan.prune || !samePrunePlan(input.reviewedPrune, initialPlan.prune))) {
1353
+ initialPlan.blockers.push('Deletion plan changed after confirmation; review the fresh plan before deploying.');
1354
+ initialPlan.readyToMigrate = false;
1355
+ initialPlan.verdict = 'blocked';
1356
+ }
1333
1357
  const base = {
1334
1358
  schemaVersion: 2,
1335
1359
  command: 'run',
@@ -1354,8 +1378,8 @@ export async function runMigration(input) {
1354
1378
  envName: environmentKey,
1355
1379
  stableKeyName,
1356
1380
  force: true,
1357
- prunePartitions: reviewedWorkspaceChanges,
1358
- prunePartitionsConfirmed: reviewedWorkspaceChanges,
1381
+ prunePartitions: reviewedWorkspaceChanges && !input.prune,
1382
+ prunePartitionsConfirmed: reviewedWorkspaceChanges && !input.prune,
1359
1383
  migrationPolicy: migrationPolicy(input),
1360
1384
  });
1361
1385
  phaseResults['database-table'] = pushed.results;
@@ -1705,6 +1729,16 @@ export async function runMigration(input) {
1705
1729
  return { ...base, verdict: 'failed', results, phaseResults, verification };
1706
1730
  }
1707
1731
  }
1732
+ if (initialPlan.prune) {
1733
+ const fresh = await buildWorkspacePrunePlan({ cwd: input.cwd, client: targetClient, resources });
1734
+ if (!samePrunePlan(initialPlan.prune, fresh)) {
1735
+ results.push({ status: 'failed', targetPath: 'workspace prune', reason: 'Deletion plan changed during upserts; review a fresh plan.' });
1736
+ return { ...base, verdict: 'failed', results, phaseResults };
1737
+ }
1738
+ const pruneResults = await applyWorkspacePrune({ cwd: input.cwd, client: targetClient,
1739
+ resources, envName: environmentKey, plan: initialPlan.prune });
1740
+ results.push(...pruneResults);
1741
+ }
1708
1742
  const verification = await planWorkspace({
1709
1743
  ...input,
1710
1744
  pulls,
@@ -132,7 +132,6 @@ export function printSyncPlan(println, input) {
132
132
  for (const item of input.items) {
133
133
  const mark = PLAN_STATUS_MARKS[item.status] || { symbol: '-', code: ANSI.dim };
134
134
  const target = item.target || item.stableKey || item.name || 'unknown';
135
- println(`${paint(mark.symbol, mark.code)} ${paint(item.status.padEnd(14), mark.code)} ${paint(target, ANSI.cyan)}`);
136
135
  const lineDiffFields = new Set((item.details || []).filter((detail) => detail.label === 'rawQuery diff' && detail.lines?.length)
137
136
  .map(() => 'rawQuery'));
138
137
  const fieldChanges = item.status === 'create'
@@ -156,6 +155,13 @@ export function printSyncPlan(println, input) {
156
155
  ...(item.details || []),
157
156
  ...(input.showHints === true ? item.hints || [] : []),
158
157
  ];
158
+ const inlineDetails = details.filter((detail) => detail.label !== 'reason'
159
+ && (detail.label !== 'hints' || input.showHints === true) && !detail.lines?.length && !detail.diffs?.length)
160
+ .map((detail) => {
161
+ const value = planDetailValue(detail.values).replace(/\s+/g, ' ').trim();
162
+ return value ? `${detail.label.replace(/\s+/g, ' ')}: ${value}` : '';
163
+ }).filter(Boolean);
164
+ println(`${paint(mark.symbol, mark.code)} ${paint(item.status.padEnd(14), mark.code)} ${paint(target.replace(/\s+/g, ' '), ANSI.cyan)}${inlineDetails.length ? ` | ${inlineDetails.join(' | ')}` : ''}`);
159
165
  for (const detail of details) {
160
166
  if (detail.label === 'reason') {
161
167
  continue;
@@ -179,10 +185,6 @@ export function printSyncPlan(println, input) {
179
185
  }
180
186
  continue;
181
187
  }
182
- const value = planDetailValue(detail.values);
183
- if (value) {
184
- println(` ${paint(detail.label.padEnd(14), ANSI.dim)} ${value}`);
185
- }
186
188
  }
187
189
  }
188
190
  const summary = Object.entries(input.counts)
package/dist/src/ui.js CHANGED
@@ -175,8 +175,8 @@ function renderCommandCatalog() {
175
175
  commandRow('revo metadata apply [--project <name>] --yes [--skip-partitions]', 'Populate missing stable-key metadata'),
176
176
  commandRow('revo pull --all|--resources <list> --yes [--skip-groups] [--force] [--json]', 'Build the repository workspace from the configured runtime source'),
177
177
  commandRow('revo diff [--json]', 'Show only workspace-to-target resource differences without writes'),
178
- commandRow('revo plan [--force] [--strict] [--json] [--hints]', 'Plan deployment of tracked workspace resources to the configured runtime target without writes'),
179
- commandRow('revo deploy --yes [--force] [--json]', 'Deploy tracked workspace resources to the configured runtime target in dependency order'),
178
+ commandRow('revo plan [--prune] [--out file] [--force] [--strict] [--json] [--hints]', 'Plan tracked workspace upserts and optional Stable Key deletions without writes'),
179
+ commandRow('revo deploy [--yes] [--prune] [--reviewed-plan file] [--force] [--json]', 'Review, confirm, deploy and prune tracked resources in dependency order'),
180
180
  commandRow('revo migrate plan --from <env> --to <env> [--resources <list>] [--skip-groups] [--force] [--json] [--hints]', 'Preview ten resource families and identity dependencies'),
181
181
  commandRow('revo migrate run --from <env> --to <env> [--resources <list>] [--skip-groups] --yes [--force] [--json]', 'Pull, plan, migrate, and verify resources in dependency order'),
182
182
  commandRow('revo migrate verify --from <env> --to <env> [--resources <list>] [--json]', 'Verify target resources against a fresh temporary source pull'),
@@ -0,0 +1,40 @@
1
+ import type { RevoClient } from './client.ts';
2
+ import { type ResourceRecord } from './resource-inventory.ts';
3
+ import type { WorkspaceSyncResult } from './sync-output.ts';
4
+ import type { TrackableResourceType } from './tracked-resources.ts';
5
+ export type WorkspacePruneItem = {
6
+ resource: TrackableResourceType;
7
+ stableKey: string;
8
+ targetId: string;
9
+ name: string;
10
+ version: number | null;
11
+ targetHash: string;
12
+ };
13
+ export type WorkspacePrunePlan = {
14
+ items: WorkspacePruneItem[];
15
+ blockers: string[];
16
+ };
17
+ type Inventory = Partial<Record<TrackableResourceType, ResourceRecord[]>>;
18
+ type LocalManifests = Partial<Record<TrackableResourceType, Map<string, Record<string, unknown>>>>;
19
+ export declare function readPruneManifests(cwd: string, resources: readonly TrackableResourceType[]): LocalManifests;
20
+ export declare function planWorkspacePrune(input: {
21
+ resources: readonly TrackableResourceType[];
22
+ inventory: Inventory;
23
+ local: LocalManifests;
24
+ stableKeyName: string;
25
+ actorId?: string;
26
+ }): WorkspacePrunePlan;
27
+ export declare function buildWorkspacePrunePlan(input: {
28
+ cwd: string;
29
+ client: RevoClient;
30
+ resources: readonly TrackableResourceType[];
31
+ }): Promise<WorkspacePrunePlan>;
32
+ export declare function samePrunePlan(left: WorkspacePrunePlan, right: WorkspacePrunePlan): boolean;
33
+ export declare function applyWorkspacePrune(input: {
34
+ cwd: string;
35
+ client: RevoClient;
36
+ resources: readonly TrackableResourceType[];
37
+ envName: string;
38
+ plan: WorkspacePrunePlan;
39
+ }): Promise<WorkspaceSyncResult[]>;
40
+ export {};
@@ -0,0 +1,363 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { hashStable, readComponentLock, removeComponentLockBaseline, writeComponentLock } from "./component-lock.js";
4
+ import { readProjectStableKeyName } from "./project.js";
5
+ import { readResourceInventory, resourceIdOf } from "./resource-inventory.js";
6
+ import { normalizeStableKeyValue, readConfiguredResourceMetadataStableKey } from "./resource-metadata.js";
7
+ import { findManifestFiles, isRecord, requireProjectLayout } from "./resource-syncs/util.js";
8
+ const manifests = {
9
+ component: ['Components', 'component.json'],
10
+ 'job-template': ['JobTemplates', 'job-template.json'],
11
+ endpoint: ['Endpoints', 'endpoint.json'],
12
+ schedule: ['Schedules', 'schedule.json'],
13
+ event: ['Events', 'event.json'],
14
+ 'database-table': ['DatabaseTables', 'database-table.json'],
15
+ 'database-view': ['DatabaseViews', 'database-view.json'],
16
+ group: ['Groups', 'group.json'],
17
+ 'role-group': ['RoleGroups', 'role-group.json'],
18
+ 'service-account': ['ServiceAccounts', 'service-account.json'],
19
+ };
20
+ const deletionOrder = [
21
+ 'event', 'schedule', 'endpoint', 'job-template', 'component',
22
+ 'database-view', 'database-table', 'role-group', 'service-account', 'group',
23
+ ];
24
+ function key(resource, identity) {
25
+ return `${resource}:${normalizeStableKeyValue(identity)}`;
26
+ }
27
+ function active(record) {
28
+ return !record.deletedAt && !record.deletedBy;
29
+ }
30
+ export function readPruneManifests(cwd, resources) {
31
+ const { workspaceRoot } = requireProjectLayout(cwd, 'Workspace prune');
32
+ const stableKeyName = readProjectStableKeyName(cwd);
33
+ const result = {};
34
+ for (const resource of resources) {
35
+ const [directory, file] = manifests[resource];
36
+ const files = findManifestFiles(path.join(workspaceRoot, directory), file);
37
+ if (resource === 'database-table') {
38
+ files.push(...findManifestFiles(path.join(workspaceRoot, 'DatabaseSchemas'), 'database-schema.json'));
39
+ }
40
+ const entries = new Map();
41
+ for (const filename of files) {
42
+ const manifest = JSON.parse(fs.readFileSync(filename, 'utf8'));
43
+ if (!isRecord(manifest))
44
+ throw new Error(`Invalid prune manifest: ${filename}.`);
45
+ const stableKey = resource === 'component'
46
+ ? readConfiguredResourceMetadataStableKey(manifest, stableKeyName)
47
+ : typeof manifest.stableKey === 'string' ? manifest.stableKey : null;
48
+ if (!stableKey)
49
+ continue;
50
+ const identity = normalizeStableKeyValue(stableKey);
51
+ if (!identity)
52
+ throw new Error(`Empty Stable Key in ${filename}.`);
53
+ if (entries.has(identity))
54
+ throw new Error(`Duplicate local ${resource} Stable Key "${stableKey}"; prune blocked.`);
55
+ entries.set(identity, manifest);
56
+ }
57
+ result[resource] = entries;
58
+ }
59
+ return result;
60
+ }
61
+ function localReferences(resource, manifest) {
62
+ const refs = [];
63
+ const add = (family, value) => {
64
+ if (typeof value === 'string' && value)
65
+ refs.push({ resource: family, identity: value });
66
+ };
67
+ if (resource === 'job-template' && isRecord(manifest.component))
68
+ add('component', manifest.component.stableKey);
69
+ if (resource === 'endpoint') {
70
+ for (const binding of [manifest.execution, manifest.schema]) {
71
+ if (isRecord(binding))
72
+ add('component', binding.stableKey);
73
+ }
74
+ }
75
+ if ((resource === 'event' || resource === 'schedule') && isRecord(manifest.target)) {
76
+ add('job-template', manifest.target.jobTemplateStableKey);
77
+ add('database-view', manifest.target.databaseViewStableKey);
78
+ }
79
+ if (resource === 'database-view' && Array.isArray(manifest.sources)) {
80
+ for (const source of manifest.sources)
81
+ if (isRecord(source))
82
+ add('database-table', source.databaseStableKey);
83
+ }
84
+ if (resource === 'database-table')
85
+ add('database-table', manifest.parentStableKey);
86
+ if (isRecord(manifest.owner)) {
87
+ if (manifest.owner.type === 'group')
88
+ add('group', manifest.owner.stableKey);
89
+ if (manifest.owner.type === 'service-account')
90
+ add('service-account', manifest.owner.stableKey);
91
+ }
92
+ if (isRecord(manifest.executionPrincipal))
93
+ add('service-account', manifest.executionPrincipal.stableKey);
94
+ return refs;
95
+ }
96
+ function remoteReferences(resource, record, tables) {
97
+ const refs = [];
98
+ const add = (family, value) => {
99
+ if (typeof value === 'string' && value)
100
+ refs.push({ resource: family, identity: value });
101
+ };
102
+ if (resource === 'job-template' || resource === 'endpoint')
103
+ add('component', record.componentId);
104
+ if (resource === 'endpoint' && isRecord(record.options))
105
+ add('component', record.options.componentSchemaId);
106
+ if (resource === 'job-template')
107
+ add('service-account', record.triggerUser);
108
+ if (resource === 'schedule' || resource === 'event') {
109
+ add(record.targetType === 'JOB_TEMPLATE' ? 'job-template' : 'database-view', record.targetId);
110
+ }
111
+ if (resource === 'database-view' && Array.isArray(record.sourceDatabaseIds)) {
112
+ for (const id of record.sourceDatabaseIds)
113
+ add('database-table', id);
114
+ }
115
+ if (resource === 'database-table') {
116
+ add('database-table', record.parentDatabaseId || record.parentId);
117
+ if (isRecord(record.parent))
118
+ add('database-table', record.parent.databaseId || record.parent.id);
119
+ const name = typeof record.parent === 'string' ? record.parent : isRecord(record.parent) ? record.parent.name : undefined;
120
+ if (typeof name === 'string') {
121
+ // The API can return a partition parent by physical name rather than ID.
122
+ // Include every matching parent; ambiguity must not hide a dependency.
123
+ for (const table of tables)
124
+ if (table.name === name)
125
+ add('database-table', resourceIdOf(table));
126
+ }
127
+ }
128
+ if (record.ownerType === 'GROUP')
129
+ add('group', record.ownerId);
130
+ if (record.ownerType === 'USER')
131
+ add('service-account', record.ownerId);
132
+ return refs;
133
+ }
134
+ function resourceHash(record) {
135
+ // Definition/version changes fence deletion. Audit timestamps, counts and activity
136
+ // can change while upserts run without changing the definition being reviewed.
137
+ const { lastUpdateAt, lastUpdateBy, createdAt, createdBy, memberCount, ...definition } = record;
138
+ return hashStable(definition);
139
+ }
140
+ export function planWorkspacePrune(input) {
141
+ const blockers = [];
142
+ const candidates = new Map();
143
+ const byId = new Map();
144
+ for (const [family, records] of Object.entries(input.inventory)) {
145
+ const resource = family;
146
+ const keys = new Set();
147
+ for (const record of records || []) {
148
+ if (!active(record))
149
+ continue;
150
+ const id = resourceIdOf(record);
151
+ if (!id)
152
+ throw new Error(`Invalid ${resource} inventory: missing target ID.`);
153
+ if (byId.has(key(resource, id)))
154
+ throw new Error(`Repeated ${resource} target ID "${id}".`);
155
+ const stableKey = readConfiguredResourceMetadataStableKey(record, input.stableKeyName);
156
+ byId.set(key(resource, id), { resource, record, stableKey });
157
+ if (!stableKey)
158
+ continue;
159
+ const identity = normalizeStableKeyValue(stableKey);
160
+ if (keys.has(identity))
161
+ blockers.push(`Duplicate target ${resource} Stable Key "${stableKey}"; prune blocked.`);
162
+ keys.add(identity);
163
+ if (!input.resources.includes(resource) || input.local[resource]?.has(identity))
164
+ continue;
165
+ if (resource === 'service-account' && (record.serviceAccount !== true || id === input.actorId)) {
166
+ blockers.push(`Cannot prune the authenticated account or a human account "${stableKey}".`);
167
+ }
168
+ if (resource === 'service-account' && !input.actorId)
169
+ blockers.push('Cannot determine authenticated account identity; service-account prune blocked.');
170
+ if (record.systemManaged === true || record.system === true) {
171
+ blockers.push(`Cannot prune system-managed ${resource} "${stableKey}".`);
172
+ }
173
+ if (resource === 'component' && [...(input.local.component?.values() || [])].some((manifest) => manifest.componentId === id || manifest.id === id)) {
174
+ blockers.push(`Local component still has target ID "${id}"; prune blocked.`);
175
+ }
176
+ candidates.set(key(resource, id), {
177
+ resource, stableKey, targetId: id, name: String(record.name || stableKey),
178
+ version: typeof record.version === 'number' ? record.version : null,
179
+ targetHash: resourceHash(record),
180
+ });
181
+ }
182
+ }
183
+ const removedKeys = new Set([...candidates.values()].map((item) => key(item.resource, item.stableKey)));
184
+ for (const [family, entries] of Object.entries(input.local)) {
185
+ for (const [identity, manifest] of entries || []) {
186
+ for (const reference of localReferences(family, manifest)) {
187
+ if (removedKeys.has(key(reference.resource, reference.identity))) {
188
+ blockers.push(`Retained ${family} "${identity}" references ${reference.resource} "${reference.identity}" planned for deletion.`);
189
+ }
190
+ }
191
+ }
192
+ }
193
+ const dependencies = new Map();
194
+ for (const [idKey, target] of byId) {
195
+ for (const reference of remoteReferences(target.resource, target.record, input.inventory['database-table'] || [])) {
196
+ const referenced = key(reference.resource, reference.identity);
197
+ if (!candidates.has(referenced))
198
+ continue;
199
+ if (candidates.has(idKey)) {
200
+ const dependents = dependencies.get(referenced) || new Set();
201
+ dependents.add(idKey);
202
+ dependencies.set(referenced, dependents);
203
+ }
204
+ else {
205
+ const desired = target.stableKey ? input.local[target.resource]?.get(normalizeStableKeyValue(target.stableKey)) : undefined;
206
+ const removed = candidates.get(referenced);
207
+ // A managed retained consumer can release the old reference during upsert.
208
+ // An unmanaged or out-of-scope consumer must never be removed implicitly.
209
+ const preservesReference = desired && (((target.resource === 'group' || target.resource === 'service-account') && !isRecord(desired.owner))
210
+ || (target.resource === 'job-template' && removed.resource === 'service-account' && !isRecord(desired.executionPrincipal)));
211
+ if (!desired || preservesReference || localReferences(target.resource, desired).some((ref) => key(ref.resource, ref.identity) === key(removed.resource, removed.stableKey))) {
212
+ blockers.push(`${removed.resource} "${removed.stableKey}" is still referenced by retained ${target.resource} "${target.stableKey || resourceIdOf(target.record)}".`);
213
+ }
214
+ }
215
+ }
216
+ }
217
+ const items = [];
218
+ const remaining = new Map(candidates);
219
+ while (remaining.size) {
220
+ const next = [...remaining.entries()]
221
+ .filter(([idKey]) => ![...(dependencies.get(idKey) || [])].some((dependent) => remaining.has(dependent)))
222
+ .sort(([, left], [, right]) => deletionOrder.indexOf(left.resource) - deletionOrder.indexOf(right.resource)
223
+ || left.stableKey.localeCompare(right.stableKey))[0];
224
+ if (!next) {
225
+ blockers.push('Deletion dependency cycle; prune blocked.');
226
+ break;
227
+ }
228
+ items.push(next[1]);
229
+ remaining.delete(next[0]);
230
+ }
231
+ return { items, blockers: [...new Set(blockers)].sort() };
232
+ }
233
+ export async function buildWorkspacePrunePlan(input) {
234
+ const resources = new Set(input.resources);
235
+ // Include unmanaged and out-of-scope consumers in dependency checks.
236
+ if (resources.has('component')) {
237
+ resources.add('job-template');
238
+ resources.add('endpoint');
239
+ }
240
+ if (resources.has('job-template')) {
241
+ resources.add('event');
242
+ resources.add('schedule');
243
+ }
244
+ if (resources.has('database-table')) {
245
+ resources.add('database-view');
246
+ }
247
+ if (resources.has('database-view')) {
248
+ resources.add('event');
249
+ resources.add('schedule');
250
+ }
251
+ if (resources.has('group') || resources.has('service-account')) {
252
+ resources.add('group');
253
+ resources.add('service-account');
254
+ resources.add('job-template');
255
+ }
256
+ const local = readPruneManifests(input.cwd, input.resources);
257
+ const inventory = {};
258
+ for (const resource of resources) {
259
+ const records = [];
260
+ if (resource === 'service-account') {
261
+ // Human owners also block Group/Account deletion. Keep the client sanitization
262
+ // and sensitive-account trace redaction; never inventory credentials.
263
+ const { serviceAccounts } = await input.client.listAllServiceAccounts({ includeHumans: true });
264
+ for (const account of serviceAccounts) {
265
+ const id = resourceIdOf(account);
266
+ const detail = await input.client.getAccount(id);
267
+ if (!id || resourceIdOf(detail) !== id)
268
+ throw new Error('Incomplete account ownership inventory; prune blocked.');
269
+ records.push(detail);
270
+ }
271
+ inventory[resource] = records;
272
+ continue;
273
+ }
274
+ for await (const entry of readResourceInventory(input.client, resource)) {
275
+ if (!entry.resource || resourceIdOf(entry.resource) !== entry.listedId)
276
+ throw new Error(`Incomplete ${resource} inventory; prune blocked.`);
277
+ records.push(entry.resource);
278
+ }
279
+ inventory[resource] = records;
280
+ }
281
+ const me = resources.has('service-account') ? await input.client.me() : undefined;
282
+ const profile = isRecord(me) && isRecord(me.data) ? me.data : me;
283
+ const actorId = isRecord(profile) && isRecord(profile.user) ? String(profile.user.userId || '')
284
+ : isRecord(profile) ? String(profile.userId || '') : undefined;
285
+ return planWorkspacePrune({ resources: input.resources, local, inventory, stableKeyName: readProjectStableKeyName(input.cwd), actorId });
286
+ }
287
+ export function samePrunePlan(left, right) {
288
+ return hashStable(left) === hashStable(right);
289
+ }
290
+ function clearPruneBaseline(cwd, envName, item) {
291
+ const { projectRoot } = requireProjectLayout(cwd, 'Workspace prune');
292
+ const lock = readComponentLock(projectRoot);
293
+ if (item.resource === 'component') {
294
+ const identity = { mode: 'stableKey', metadataProperty: readProjectStableKeyName(cwd) };
295
+ const match = Object.entries(lock.components).find(([entryKey, value]) => normalizeStableKeyValue(value.stableKey || entryKey) === normalizeStableKeyValue(item.stableKey));
296
+ if (match?.[1].environments?.[envName]?.remoteComponentId === item.targetId) {
297
+ removeComponentLockBaseline(projectRoot, identity, match[0], item.targetId, envName);
298
+ }
299
+ return;
300
+ }
301
+ const fields = {
302
+ 'job-template': 'jobTemplates', endpoint: 'endpoints', schedule: 'schedules', event: 'events',
303
+ 'database-table': 'databaseSchemas', 'database-view': 'databaseViews', group: 'groups',
304
+ 'role-group': 'roleGroups', 'service-account': 'serviceAccounts',
305
+ };
306
+ const entries = lock[fields[item.resource]];
307
+ const entry = Object.values(entries).find((value) => normalizeStableKeyValue(value.stableKey) === normalizeStableKeyValue(item.stableKey));
308
+ if (entry?.environments[envName]) {
309
+ if (item.resource === 'database-table' && 'parentStableKey' in entry && entry.parentStableKey) {
310
+ lock.databaseSchemas[entry.stableKey].environments[envName] = {
311
+ remoteHash: entry.environments[envName].remoteHash,
312
+ tombstone: { deletedAt: new Date().toISOString(), parentStableKey: entry.parentStableKey },
313
+ };
314
+ }
315
+ else
316
+ delete entry.environments[envName];
317
+ writeComponentLock(projectRoot, lock);
318
+ }
319
+ }
320
+ export async function applyWorkspacePrune(input) {
321
+ if (input.plan.blockers.length)
322
+ throw new Error('Workspace prune plan is blocked.');
323
+ const results = [];
324
+ for (const item of input.plan.items) {
325
+ let accepted = false;
326
+ try {
327
+ if (readPruneManifests(input.cwd, input.resources)[item.resource]?.has(normalizeStableKeyValue(item.stableKey))) {
328
+ throw new Error('local manifest reappeared after planning');
329
+ }
330
+ // These owning APIs can affect a table subtree or deactivate view automations.
331
+ // Recheck the complete remaining graph before invoking a cascading lifecycle.
332
+ if (item.resource === 'database-table' || item.resource === 'database-view') {
333
+ const fresh = await buildWorkspacePrunePlan(input);
334
+ if (!samePrunePlan({ ...input.plan, items: input.plan.items.slice(results.length) }, fresh)) {
335
+ throw new Error('remaining deletion dependencies changed after planning');
336
+ }
337
+ }
338
+ let current;
339
+ for await (const entry of readResourceInventory(input.client, item.resource)) {
340
+ if (resourceIdOf(entry.resource) === item.targetId && active(entry.resource))
341
+ current = entry.resource;
342
+ }
343
+ if (!current || readConfiguredResourceMetadataStableKey(current, readProjectStableKeyName(input.cwd)) !== item.stableKey
344
+ || resourceHash(current) !== item.targetHash)
345
+ throw new Error('target changed after deletion was reviewed');
346
+ await input.client.deleteWorkspaceResource(item.resource, item.targetId);
347
+ accepted = true;
348
+ for await (const entry of readResourceInventory(input.client, item.resource)) {
349
+ if (resourceIdOf(entry.resource) === item.targetId && active(entry.resource))
350
+ throw new Error('delete did not remove the resource from the active catalog');
351
+ }
352
+ clearPruneBaseline(input.cwd, input.envName, item);
353
+ results.push({ status: 'pruned', targetPath: `${item.resource}:${item.stableKey}` });
354
+ }
355
+ catch (error) {
356
+ results.push({ status: accepted ? 'write-unverified' : 'failed', targetPath: `${item.resource}:${item.stableKey}`,
357
+ reason: error instanceof Error ? error.message : String(error) });
358
+ // Never continue into deletion of dependencies after a failed consumer delete.
359
+ break;
360
+ }
361
+ }
362
+ return results;
363
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revoengine/cli",
3
- "version": "1.0.16",
3
+ "version": "1.0.17",
4
4
  "description": "CLI package for the RevoEngine Platform API",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",
@@ -11,7 +11,7 @@
11
11
  "scripts": {
12
12
  "build": "npm run clean && tsc -p tsconfig.build.json",
13
13
  "clean": "node --input-type=module -e \"import fs from 'node:fs'; fs.rmSync('dist', { recursive: true, force: true });\"",
14
- "check": "node --input-type=module -e \"await import('./src/config.ts'); await import('./src/legacy.ts'); await import('./src/http-trace.ts'); await import('./src/request-queue.ts'); await import('./src/client.ts'); await import('./src/component-lock.ts'); await import('./src/diff-details.ts'); await import('./src/resource-metadata.ts'); await import('./src/tracked-resources.ts'); await import('./src/resource-inventory.ts'); await import('./src/metadata-backfill.ts'); await import('./src/workspace-component.ts'); await import('./src/workspace-resource.ts'); await import('./src/database-table-artifacts.ts'); await import('./src/project.ts'); await import('./src/prompt.ts'); await import('./src/runtime-view.ts'); await import('./src/spinner.ts'); await import('./src/types.ts'); await import('./src/utils.ts'); await import('./src/resource-syncs/util.ts'); await import('./src/resource-syncs/database-table-sync.ts'); await import('./src/resource-syncs/database-view-sync.ts'); await import('./src/resource-syncs/endpoint-sync.ts'); await import('./src/resource-syncs/group-sync.ts'); await import('./src/resource-syncs/role-group-sync.ts'); await import('./src/resource-syncs/job-template-sync.ts'); await import('./src/resource-syncs/schedule-sync.ts'); await import('./src/resource-syncs/event-sync.ts'); await import('./src/resource-syncs/account-principal.ts'); await import('./src/resource-syncs/identity-migration.ts'); await import('./src/resource-syncs/service-account-sync.ts'); await import('./src/commands/service-accounts.ts'); await import('./src/migration.ts'); await import('./src/workspace-diff.ts'); await import('./src/sync-output.ts'); await import('./src/ui.ts'); await import('./src/update-notifier.ts'); await import('./src/env-sync.ts'); await import('./src/commands/auth.ts'); await import('./src/commands/component.ts'); await import('./src/commands/database-tables.ts'); await import('./src/commands/database-views.ts'); await import('./src/commands/endpoints.ts'); await import('./src/commands/env.ts'); await import('./src/commands/events.ts'); await import('./src/commands/groups.ts'); await import('./src/commands/info.ts'); await import('./src/commands/job-templates.ts'); await import('./src/commands/metadata.ts'); await import('./src/commands/migrate.ts'); await import('./src/commands/request.ts'); await import('./src/commands/role-groups.ts'); await import('./src/commands/search.ts'); await import('./src/commands/schedules.ts'); await import('./src/commands/terminal-service.ts'); await import('./src/commands/terminal-browser.ts'); await import('./src/commands/terminal-image.ts'); await import('./src/commands/terminal-sandbox.ts'); await import('./src/commands/terminal-patch.ts'); await import('./src/commands/terminal-patch-worker.ts'); await import('./src/commands/terminal.ts'); await import('./src/cli.ts'); await import('./src/index.ts'); await import('./bin/revo.ts'); await import('./scripts/dev.ts')\"",
14
+ "check": "node --input-type=module -e \"await import('./src/config.ts'); await import('./src/legacy.ts'); await import('./src/http-trace.ts'); await import('./src/request-queue.ts'); await import('./src/client.ts'); await import('./src/component-lock.ts'); await import('./src/diff-details.ts'); await import('./src/resource-metadata.ts'); await import('./src/tracked-resources.ts'); await import('./src/resource-inventory.ts'); await import('./src/metadata-backfill.ts'); await import('./src/workspace-component.ts'); await import('./src/workspace-resource.ts'); await import('./src/database-table-artifacts.ts'); await import('./src/project.ts'); await import('./src/prompt.ts'); await import('./src/runtime-view.ts'); await import('./src/spinner.ts'); await import('./src/types.ts'); await import('./src/utils.ts'); await import('./src/resource-syncs/util.ts'); await import('./src/resource-syncs/database-table-sync.ts'); await import('./src/resource-syncs/database-view-sync.ts'); await import('./src/resource-syncs/endpoint-sync.ts'); await import('./src/resource-syncs/group-sync.ts'); await import('./src/resource-syncs/role-group-sync.ts'); await import('./src/resource-syncs/job-template-sync.ts'); await import('./src/resource-syncs/schedule-sync.ts'); await import('./src/resource-syncs/event-sync.ts'); await import('./src/resource-syncs/account-principal.ts'); await import('./src/resource-syncs/identity-migration.ts'); await import('./src/resource-syncs/service-account-sync.ts'); await import('./src/commands/service-accounts.ts'); await import('./src/migration.ts'); await import('./src/workspace-diff.ts'); await import('./src/workspace-prune.ts'); await import('./src/sync-output.ts'); await import('./src/ui.ts'); await import('./src/update-notifier.ts'); await import('./src/env-sync.ts'); await import('./src/commands/auth.ts'); await import('./src/commands/component.ts'); await import('./src/commands/database-tables.ts'); await import('./src/commands/database-views.ts'); await import('./src/commands/endpoints.ts'); await import('./src/commands/env.ts'); await import('./src/commands/events.ts'); await import('./src/commands/groups.ts'); await import('./src/commands/info.ts'); await import('./src/commands/job-templates.ts'); await import('./src/commands/metadata.ts'); await import('./src/commands/migrate.ts'); await import('./src/commands/request.ts'); await import('./src/commands/role-groups.ts'); await import('./src/commands/search.ts'); await import('./src/commands/schedules.ts'); await import('./src/commands/terminal-service.ts'); await import('./src/commands/terminal-browser.ts'); await import('./src/commands/terminal-image.ts'); await import('./src/commands/terminal-sandbox.ts'); await import('./src/commands/terminal-patch.ts'); await import('./src/commands/terminal-patch-worker.ts'); await import('./src/commands/terminal.ts'); await import('./src/cli.ts'); await import('./src/index.ts'); await import('./bin/revo.ts'); await import('./scripts/dev.ts')\"",
15
15
  "dev": "node ./scripts/dev.ts",
16
16
  "prepack": "npm run build",
17
17
  "test": "node --test ./test/*.test.ts",