@fuzdev/fuz_gitops 0.71.0 → 0.73.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +13 -6
  2. package/dist/changeset_generator.d.ts.map +1 -1
  3. package/dist/changeset_generator.js +2 -16
  4. package/dist/changeset_reader.d.ts +1 -1
  5. package/dist/changeset_reader.d.ts.map +1 -1
  6. package/dist/dependency_graph.js +1 -1
  7. package/dist/git_operations.d.ts +5 -0
  8. package/dist/git_operations.d.ts.map +1 -1
  9. package/dist/git_operations.js +5 -0
  10. package/dist/gitops_analyze.task.d.ts +1 -0
  11. package/dist/gitops_analyze.task.d.ts.map +1 -1
  12. package/dist/gitops_analyze.task.js +12 -17
  13. package/dist/gitops_plan.task.d.ts +1 -0
  14. package/dist/gitops_plan.task.d.ts.map +1 -1
  15. package/dist/gitops_plan.task.js +9 -2
  16. package/dist/gitops_publish.task.d.ts +3 -2
  17. package/dist/gitops_publish.task.d.ts.map +1 -1
  18. package/dist/gitops_publish.task.js +90 -26
  19. package/dist/gitops_run.task.d.ts +2 -1
  20. package/dist/gitops_run.task.d.ts.map +1 -1
  21. package/dist/gitops_run.task.js +40 -7
  22. package/dist/gitops_sync.task.d.ts +1 -0
  23. package/dist/gitops_sync.task.d.ts.map +1 -1
  24. package/dist/gitops_sync.task.js +16 -2
  25. package/dist/gitops_task_helpers.d.ts +16 -2
  26. package/dist/gitops_task_helpers.d.ts.map +1 -1
  27. package/dist/gitops_task_helpers.js +11 -3
  28. package/dist/gitops_validate.task.d.ts +1 -0
  29. package/dist/gitops_validate.task.d.ts.map +1 -1
  30. package/dist/gitops_validate.task.js +20 -20
  31. package/dist/graph_validation.d.ts +16 -1
  32. package/dist/graph_validation.d.ts.map +1 -1
  33. package/dist/graph_validation.js +15 -0
  34. package/dist/local_repo.d.ts +22 -10
  35. package/dist/local_repo.d.ts.map +1 -1
  36. package/dist/local_repo.js +92 -75
  37. package/dist/log_helpers.d.ts +0 -5
  38. package/dist/log_helpers.d.ts.map +1 -1
  39. package/dist/log_helpers.js +8 -19
  40. package/dist/multi_repo_publisher.d.ts +29 -2
  41. package/dist/multi_repo_publisher.d.ts.map +1 -1
  42. package/dist/multi_repo_publisher.js +307 -233
  43. package/dist/operations.d.ts +6 -26
  44. package/dist/operations.d.ts.map +1 -1
  45. package/dist/operations_defaults.d.ts.map +1 -1
  46. package/dist/operations_defaults.js +1 -19
  47. package/dist/output_helpers.d.ts.map +1 -1
  48. package/dist/output_helpers.js +7 -6
  49. package/dist/paths.d.ts +0 -4
  50. package/dist/paths.d.ts.map +1 -1
  51. package/dist/paths.js +0 -4
  52. package/dist/publish_gate.d.ts +44 -0
  53. package/dist/publish_gate.d.ts.map +1 -0
  54. package/dist/publish_gate.js +32 -0
  55. package/dist/publish_steps.d.ts +60 -0
  56. package/dist/publish_steps.d.ts.map +1 -0
  57. package/dist/publish_steps.js +113 -0
  58. package/dist/publishing_event.d.ts +123 -0
  59. package/dist/publishing_event.d.ts.map +1 -0
  60. package/dist/publishing_event.js +140 -0
  61. package/dist/publishing_event_handler.d.ts +42 -0
  62. package/dist/publishing_event_handler.d.ts.map +1 -0
  63. package/dist/publishing_event_handler.js +75 -0
  64. package/dist/publishing_plan.d.ts +1 -2
  65. package/dist/publishing_plan.d.ts.map +1 -1
  66. package/dist/publishing_plan.js +18 -1
  67. package/dist/publishing_plan_helpers.d.ts +1 -1
  68. package/dist/publishing_plan_helpers.d.ts.map +1 -1
  69. package/dist/publishing_plan_helpers.js +2 -15
  70. package/dist/publishing_plan_logging.d.ts.map +1 -1
  71. package/dist/publishing_plan_logging.js +15 -23
  72. package/dist/repo_ops.d.ts +1 -1
  73. package/dist/repo_ops.js +1 -1
  74. package/dist/version_utils.d.ts +17 -3
  75. package/dist/version_utils.d.ts.map +1 -1
  76. package/dist/version_utils.js +22 -0
  77. package/package.json +6 -7
  78. package/src/lib/changeset_generator.ts +10 -19
  79. package/src/lib/changeset_reader.ts +1 -2
  80. package/src/lib/dependency_graph.ts +1 -1
  81. package/src/lib/git_operations.ts +5 -0
  82. package/src/lib/gitops_analyze.task.ts +18 -23
  83. package/src/lib/gitops_plan.task.ts +10 -2
  84. package/src/lib/gitops_publish.task.ts +100 -25
  85. package/src/lib/gitops_run.task.ts +39 -7
  86. package/src/lib/gitops_sync.task.ts +18 -3
  87. package/src/lib/gitops_task_helpers.ts +20 -3
  88. package/src/lib/gitops_validate.task.ts +30 -22
  89. package/src/lib/graph_validation.ts +26 -0
  90. package/src/lib/local_repo.ts +114 -83
  91. package/src/lib/log_helpers.ts +8 -26
  92. package/src/lib/multi_repo_publisher.ts +387 -269
  93. package/src/lib/operations.ts +6 -22
  94. package/src/lib/operations_defaults.ts +1 -19
  95. package/src/lib/output_helpers.ts +7 -6
  96. package/src/lib/paths.ts +0 -5
  97. package/src/lib/publish_gate.ts +53 -0
  98. package/src/lib/publish_steps.ts +149 -0
  99. package/src/lib/publishing_event.ts +151 -0
  100. package/src/lib/publishing_event_handler.ts +98 -0
  101. package/src/lib/publishing_plan.ts +23 -3
  102. package/src/lib/publishing_plan_helpers.ts +5 -18
  103. package/src/lib/publishing_plan_logging.ts +19 -39
  104. package/src/lib/repo_ops.ts +1 -1
  105. package/src/lib/version_utils.ts +30 -9
  106. package/dist/npm_install_helpers.d.ts +0 -23
  107. package/dist/npm_install_helpers.d.ts.map +0 -1
  108. package/dist/npm_install_helpers.js +0 -60
  109. package/dist/semver.d.ts +0 -26
  110. package/dist/semver.d.ts.map +0 -1
  111. package/dist/semver.js +0 -137
  112. package/dist/serialization_types.d.ts +0 -59
  113. package/dist/serialization_types.d.ts.map +0 -1
  114. package/dist/serialization_types.js +0 -42
  115. package/src/lib/npm_install_helpers.ts +0 -85
  116. package/src/lib/semver.ts +0 -170
  117. package/src/lib/serialization_types.ts +0 -92
@@ -2,14 +2,42 @@ import { TaskError } from '@fuzdev/gro';
2
2
  import { join } from 'node:path';
3
3
  import { styleText as st } from 'node:util';
4
4
  import { update_package_json } from './dependency_updater.js';
5
- import { validate_dependency_graph } from './graph_validation.js';
6
- import { needs_update, is_breaking_change, detect_bump_type } from './version_utils.js';
5
+ import { generate_publishing_plan, } from './publishing_plan.js';
7
6
  import { default_gitops_operations } from './operations_defaults.js';
8
- import { GITOPS_MAX_ITERATIONS_DEFAULT, GITOPS_NPM_WAIT_TIMEOUT_DEFAULT, } from './gitops_constants.js';
9
- import { install_with_cache_healing } from './npm_install_helpers.js';
7
+ import { GITOPS_NPM_WAIT_TIMEOUT_DEFAULT } from './gitops_constants.js';
8
+ import { summarize_events, } from './publishing_event.js';
9
+ import { capture_handler, multi_handler, } from './publishing_event_handler.js';
10
10
  export const publish_repos = async (repos, options) => {
11
+ const { log, ops = default_gitops_operations } = options;
12
+ // Convenience entry: generate the plan, then execute it. Callers that already hold a
13
+ // plan (e.g. to display and confirm it first) call `execute_publishing_plan` directly,
14
+ // so the plan is generated exactly once per command.
15
+ const plan = await generate_publishing_plan(repos, { log, ops: ops.changeset });
16
+ return execute_publishing_plan(repos, plan, options);
17
+ };
18
+ /**
19
+ * Executes a frozen publishing plan in a single linear pass — the "dumb executor" half of
20
+ * the zap model. The plan is the single source of truth; this re-derives nothing.
21
+ *
22
+ * Fails loud when the plan couldn't be fully computed (`plan.errors`): a wetrun aborts
23
+ * before any side effect, a dry run still reports the partial cascade but returns
24
+ * `ok: false`. This is the single error gate — `--no-plan` can't bypass it.
25
+ */
26
+ export const execute_publishing_plan = async (repos, plan, options) => {
11
27
  const start_time = Date.now();
12
- const { wetrun, update_deps, log, ops = default_gitops_operations } = options;
28
+ const { wetrun, log, ops = default_gitops_operations } = options;
29
+ // Fail loud on an incomplete plan. Executing one with errors would silently skip the
30
+ // affected packages. A wetrun aborts before touching npm or git; a dry run proceeds
31
+ // (no side effects) but the result is not ok (see the summary below).
32
+ if (wetrun && plan.errors.length > 0) {
33
+ throw new TaskError(`Cannot publish — the plan has ${plan.errors.length} error(s):\n ${plan.errors.join('\n ')}`);
34
+ }
35
+ // Capture every event for the result; also forward to the caller's sink if provided.
36
+ const capture = capture_handler();
37
+ const events_handler = options.events ? multi_handler([options.events, capture]) : capture;
38
+ const emit = (event) => {
39
+ events_handler.emit(event);
40
+ };
13
41
  // Preflight checks (skip for dry runs since we're not actually publishing)
14
42
  if (wetrun) {
15
43
  const preflight_options = {
@@ -32,297 +60,313 @@ export const publish_repos = async (repos, options) => {
32
60
  else {
33
61
  log?.info('⏭️ Skipping preflight checks (dry run)');
34
62
  }
35
- // Build dependency graph and validate
36
- const { publishing_order: order } = validate_dependency_graph(repos, {
37
- log,
38
- throw_on_prod_cycles: true,
39
- log_cycles: true,
40
- log_order: true,
41
- });
63
+ // The plan already validated the dependency graph and resolved the full cascade
64
+ // (explicit changesets, bump escalations, and auto-generated changesets) — execute its
65
+ // frozen topological order directly, re-deriving nothing.
66
+ const order = plan.publishing_order;
67
+ const plan_changes = new Map(plan.version_changes.map((vc) => [vc.package_name, vc]));
68
+ if (order.length > 0) {
69
+ log?.info(` Publishing order: ${order.join(' → ')}`);
70
+ }
71
+ emit({ event: 'run_started', wetrun, total: order.length });
42
72
  const published = new Map();
43
73
  const failed = new Map();
44
74
  const changed_repos = new Set(); // Track repos with any changes for selective deployment
45
- // Fixed-point iteration: keep publishing until no new changesets are created
46
- // This handles transitive dependency updates (auto-generated changesets)
47
- let iteration = 0;
48
- let converged = false;
49
- while (!converged && iteration < GITOPS_MAX_ITERATIONS_DEFAULT) {
50
- iteration++;
51
- log?.info(st('cyan', `\n🚀 Publishing iteration ${iteration}/${GITOPS_MAX_ITERATIONS_DEFAULT}...\n`));
52
- // Track if any packages were published in this iteration
53
- let published_in_iteration = false;
54
- let published_count = 0;
55
- // Track repos changed in THIS iteration only (for batch install)
56
- const changed_in_iteration = new Set();
57
- // Phase 1: Publish each package and immediately update dependents
58
- for (let i = 0; i < order.length; i++) {
59
- const pkg_name = order[i];
60
- const repo = repos.find((r) => r.library.name === pkg_name);
61
- if (!repo)
62
- continue;
63
- // Skip if already published in a previous iteration
64
- if (published.has(pkg_name)) {
65
- continue;
66
- }
67
- // Check for changesets (both dry and real runs)
68
- const has_result = await ops.changeset.has_changesets({ repo });
69
- if (!has_result.ok) {
70
- // Failed to check changesets
71
- const err = new Error(`Failed to check changesets: ${has_result.message}`);
75
+ // Name → repo index, built once to avoid repeated linear scans of `repos`.
76
+ const repo_by_name = new Map(repos.map((r) => [r.library.name, r]));
77
+ log?.info(st('cyan', `\n🚀 ${wetrun ? 'Publishing' : 'Dry run'}...\n`));
78
+ // Phase 1: one linear pass over the plan's topological order. The plan already
79
+ // resolved the full cascade, and publishing a package immediately rewrites every
80
+ // dependent's package.json and creates its auto-changeset — so by the time the pass
81
+ // reaches any package, all its dependencies have published and its changeset exists.
82
+ // No fixed-point loop is needed: a single pass converges by construction.
83
+ for (let i = 0; i < order.length; i++) {
84
+ const pkg_name = order[i];
85
+ const planned = plan_changes.get(pkg_name);
86
+ // Not in the plan = no changesets and no dependency updates = nothing to publish.
87
+ if (!planned) {
88
+ emit({ event: 'package_skipped', name: pkg_name, reason: 'no changesets' });
89
+ log?.info(st('yellow', ` ⚠️ Skipping ${pkg_name} - no changesets`));
90
+ continue;
91
+ }
92
+ const repo = repo_by_name.get(pkg_name);
93
+ if (!repo)
94
+ continue;
95
+ // An earlier publish may have rewritten this package's dependency ranges. No install is
96
+ // needed here: `gro publish` runs its own install (which self-heals npm's stale-cache
97
+ // ETARGET), so the package's freshly-rewritten deps are installed and healed as part of
98
+ // publishing it.
99
+ try {
100
+ // 1. Publish this package (real publish or dry-run prediction)
101
+ log?.info(st('dim', ` [${i + 1}/${order.length}] ${wetrun ? 'Publishing' : 'Would publish'} ${pkg_name}...`));
102
+ const version = await publish_single_repo(repo, options, ops, planned);
103
+ // Fail loud on drift: a real publish that lands a version the plan didn't predict
104
+ // is an invariant violation, not a routine failure. Abort and leave the dirty
105
+ // state in place — re-running re-plans from the current state (the just-published
106
+ // package no longer has changesets, so it drops out of the new plan).
107
+ if (wetrun && version.new_version !== planned.to) {
108
+ const err = new Error(`Plan drift for ${pkg_name}: published ${version.new_version} but the plan predicted ${planned.to}. ` +
109
+ `Aborting — re-run 'gro gitops_publish --wetrun' to re-plan from the current state.`);
72
110
  failed.set(pkg_name, err);
111
+ emit({ event: 'package_failed', name: pkg_name, error: err.message, code: 'drift' });
73
112
  log?.error(st('red', ` ❌ ${err.message}`));
74
113
  break;
75
114
  }
76
- if (!has_result.value) {
77
- // Skip packages without changesets
78
- // In real publish: They might get auto-changesets during dependency updates
79
- // In dry run: We can't simulate auto-changesets, so just skip
80
- if (!wetrun) {
81
- // Silent skip in dry run - plan shows which packages get auto-changesets
82
- continue;
83
- }
84
- else {
85
- log?.info(st('yellow', ` ⚠️ Skipping ${pkg_name} - no changesets`));
86
- continue;
115
+ published.set(pkg_name, version);
116
+ changed_repos.add(pkg_name); // Mark as changed for deployment
117
+ emit({
118
+ event: 'package_completed',
119
+ name: pkg_name,
120
+ old_version: version.old_version,
121
+ new_version: version.new_version,
122
+ bump_type: version.bump_type,
123
+ breaking: version.breaking,
124
+ commit: version.commit,
125
+ tag: version.tag,
126
+ });
127
+ log?.info(wetrun
128
+ ? st('green', ` ✅ Published ${pkg_name}@${version.new_version}`)
129
+ : st('cyan', ` ◇ Would publish ${pkg_name}@${version.new_version}`));
130
+ if (wetrun) {
131
+ // 2. Wait for this package to be available on NPM
132
+ log?.info(` ⏳ Waiting for ${pkg_name}@${version.new_version} on NPM...`);
133
+ const wait_result = await ops.npm.wait_for_package({
134
+ pkg: pkg_name,
135
+ version: version.new_version,
136
+ wait_options: {
137
+ max_attempts: 30,
138
+ initial_delay: 1000,
139
+ max_delay: 60000,
140
+ timeout: options.max_wait ?? GITOPS_NPM_WAIT_TIMEOUT_DEFAULT,
141
+ },
142
+ log,
143
+ });
144
+ if (!wait_result.ok) {
145
+ // Handle inline (don't throw into the generic catch): the npm-wait failure
146
+ // carries a typed `timeout` signal, so we know this is a network failure
147
+ // without sniffing the message.
148
+ const err = new Error(`Failed to wait for package: ${wait_result.message}${wait_result.timeout ? ' (timeout)' : ''}`);
149
+ failed.set(pkg_name, err);
150
+ emit({ event: 'package_failed', name: pkg_name, error: err.message, code: 'network' });
151
+ log?.error(st('red', ` ❌ Failed to publish ${pkg_name}: ${err.message}`));
152
+ break; // fail fast
87
153
  }
88
- }
89
- try {
90
- // 1. Publish this package
91
- log?.info(st('dim', ` [${i + 1}/${order.length}] Publishing ${pkg_name}...`));
92
- const version = await publish_single_repo(repo, options, ops);
93
- published.set(pkg_name, version);
94
- changed_repos.add(pkg_name); // Mark as changed for deployment
95
- // Note: don't add to changed_in_iteration - published packages don't need install
96
- // (their dependencies didn't change, only their version)
97
- published_in_iteration = true;
98
- published_count++;
99
- log?.info(st('green', ` ✅ Published ${pkg_name}@${version.new_version}`));
100
- if (wetrun) {
101
- // 2. Wait for this package to be available on NPM
102
- log?.info(` ⏳ Waiting for ${pkg_name}@${version.new_version} on NPM...`);
103
- const wait_result = await ops.npm.wait_for_package({
104
- pkg: pkg_name,
105
- version: version.new_version,
106
- wait_options: {
107
- max_attempts: 30,
108
- initial_delay: 1000,
109
- max_delay: 60000,
110
- timeout: options.max_wait ?? GITOPS_NPM_WAIT_TIMEOUT_DEFAULT,
111
- },
112
- log,
113
- });
114
- if (!wait_result.ok) {
115
- throw new Error(`Failed to wait for package: ${wait_result.message}${wait_result.timeout ? ' (timeout)' : ''}`);
154
+ emit({ event: 'npm_waited', name: pkg_name, version: version.new_version });
155
+ // 3. Update every dependent the plan says has a prod/peer dep on this package.
156
+ // This rewrites their package.json ranges and creates their auto-changeset,
157
+ // which a later step of this same pass publishes. The dependent is queued for
158
+ // a single install just before it publishes (see the top of the loop).
159
+ const dependent_updates = group_dependency_updates(plan.dependency_updates, published, (update) => update.updated_dependency === pkg_name &&
160
+ (update.type === 'dependencies' || update.type === 'peerDependencies'));
161
+ for (const [dependent_name, updates] of dependent_updates) {
162
+ const dependent_repo = repo_by_name.get(dependent_name);
163
+ if (!dependent_repo)
164
+ continue;
165
+ // A dependent republishes iff the plan gave it a version change. Private packages
166
+ // are excluded from the plan's version changes, so they take the update-only-leaf
167
+ // path: rewrite + commit their dependency ranges with NO changeset and NO
168
+ // publish/npm-wait. Publishable dependents get an auto-changeset and republish in
169
+ // turn — `gro publish` installs + heals their rewritten deps when it reaches them.
170
+ const republishes = plan_changes.has(dependent_name);
171
+ for (const [dep_name, dep_version] of updates) {
172
+ log?.info(` Updating ${dependent_name}'s dependency on ${dep_name}`);
173
+ emit({
174
+ event: 'dependency_updated',
175
+ dependent: dependent_name,
176
+ dependency: dep_name,
177
+ version: dep_version,
178
+ dep_type: dependency_update_type(plan, dependent_name, dep_name),
179
+ creates_changeset: republishes,
180
+ });
116
181
  }
117
- // 3. Update all repos that have prod/peer deps on this package
118
- if (update_deps) {
119
- for (const dependent_repo of repos) {
120
- const updates = new Map();
121
- // Check prod dependencies
122
- if (dependent_repo.dependencies?.has(pkg_name)) {
123
- const current = dependent_repo.dependencies.get(pkg_name);
124
- if (needs_update(current, version.new_version)) {
125
- updates.set(pkg_name, version.new_version);
126
- }
127
- }
128
- // Check peer dependencies
129
- if (dependent_repo.peer_dependencies?.has(pkg_name)) {
130
- const current = dependent_repo.peer_dependencies.get(pkg_name);
131
- if (needs_update(current, version.new_version)) {
132
- updates.set(pkg_name, version.new_version);
133
- }
134
- }
135
- // Apply updates if any
136
- if (updates.size > 0) {
137
- log?.info(` Updating ${dependent_repo.library.name}'s dependency on ${pkg_name}`);
138
- changed_repos.add(dependent_repo.library.name); // Mark as changed for deployment
139
- changed_in_iteration.add(dependent_repo.library.name); // Track for batch install
140
- await update_package_json(dependent_repo, updates, {
141
- strategy: options.version_strategy || 'caret',
142
- published_versions: published,
143
- log,
144
- git_ops: ops.git,
145
- });
146
- }
147
- }
182
+ changed_repos.add(dependent_name); // Mark as changed for deployment
183
+ if (republishes) {
184
+ await update_package_json(dependent_repo, updates, {
185
+ strategy: options.version_strategy || 'caret',
186
+ published_versions: published, // creates the auto-changeset
187
+ log,
188
+ git_ops: ops.git,
189
+ fs_ops: ops.fs,
190
+ });
191
+ }
192
+ else {
193
+ // update-only leaf: rewrite ranges + commit, no changeset (it won't republish)
194
+ await update_package_json(dependent_repo, updates, {
195
+ strategy: options.version_strategy || 'caret',
196
+ log,
197
+ git_ops: ops.git,
198
+ fs_ops: ops.fs,
199
+ });
148
200
  }
149
201
  }
150
202
  }
151
- catch (error) {
152
- const err = error instanceof Error ? error : new Error(String(error));
153
- failed.set(pkg_name, err);
154
- log?.error(st('red', ` ❌ Failed to publish ${pkg_name}: ${err.message}`));
155
- break; // Always fail fast on error
156
- }
157
- }
158
- // Phase 1b: Batch install dependencies for repos with updated package.json
159
- // This ensures workspace stays consistent before next iteration
160
- if (wetrun && !options.skip_install && changed_in_iteration.size > 0) {
161
- log?.info(st('cyan', '\n📦 Installing dependencies for updated repos...\n'));
162
- for (const pkg_name of changed_in_iteration) {
163
- const repo = repos.find((r) => r.library.name === pkg_name);
164
- if (!repo)
165
- continue;
166
- try {
167
- log?.info(` Installing ${pkg_name}...`);
168
- await install_with_cache_healing(repo, ops, log);
169
- log?.info(st('green', ` ✅ Installed ${pkg_name}`));
170
- }
171
- catch (error) {
172
- const err = error instanceof Error ? error : new Error(String(error));
173
- failed.set(pkg_name, err);
174
- log?.error(st('red', ` ❌ Failed to install ${pkg_name}: ${err.message}`));
175
- // Continue with other installs instead of breaking
176
- }
177
- }
178
- }
179
- // Log iteration summary
180
- if (published_count > 0) {
181
- log?.info(st('dim', `\nIteration ${iteration}: ${published_count} package(s) published\n`));
182
203
  }
183
- // Check for convergence: no packages published in this iteration
184
- if (!published_in_iteration) {
185
- converged = true;
186
- log?.info(st('green', `\n✓ Converged after ${iteration} iteration(s) - no new changesets\n`));
187
- }
188
- else if (iteration === GITOPS_MAX_ITERATIONS_DEFAULT) {
189
- // Count packages that still have changesets (not yet published)
190
- const pending_count = order.length - published.size;
191
- const estimated_iterations = Math.ceil(pending_count / 2); // Rough estimate
192
- log?.warn(st('yellow', `\n⚠️ Reached maximum iterations (${GITOPS_MAX_ITERATIONS_DEFAULT}) without full convergence\n` +
193
- ` ${pending_count} package(s) may still have changesets to process\n` +
194
- ` Estimated ${estimated_iterations} more iteration(s) needed - run 'gro gitops_publish' again\n`));
204
+ catch (error) {
205
+ const err = error instanceof Error ? error : new Error(String(error));
206
+ failed.set(pkg_name, err);
207
+ emit({
208
+ event: 'package_failed',
209
+ name: pkg_name,
210
+ error: err.message,
211
+ // TODO: emit a precise code once the npm/process ops return typed errors —
212
+ // today a publish-step cause lives in unstructured stderr, so use the honest
213
+ // coarse bucket rather than guessing 'auth'/'network'/'build' from the message.
214
+ code: 'publish',
215
+ });
216
+ log?.error(st('red', ` ❌ Failed to publish ${pkg_name}: ${err.message}`));
217
+ break; // Always fail fast on error
195
218
  }
196
219
  }
197
220
  // Phase 2: Update all dev dependencies (can have cycles)
198
- // Dev dep changes require deployment even without version bumps (rebuild needed)
199
- const dev_updated_repos = new Set();
200
- if (update_deps && published.size > 0 && wetrun) {
201
- log?.info(st('cyan', '\n🔄 Updating dev dependencies...\n'));
202
- for (const repo of repos) {
203
- const dev_updates = new Map();
204
- // Check dev dependencies only
205
- if (repo.dev_dependencies) {
206
- for (const [dep_name, current_version] of repo.dev_dependencies) {
207
- const published_version = published.get(dep_name);
208
- if (published_version && needs_update(current_version, published_version.new_version)) {
209
- dev_updates.set(dep_name, published_version.new_version);
210
- }
211
- }
212
- }
213
- if (dev_updates.size > 0) {
214
- log?.info(` Updating ${dev_updates.size} dev dependencies in ${repo.library.name}`);
215
- changed_repos.add(repo.library.name); // Mark as changed for deployment
216
- dev_updated_repos.add(repo.library.name); // Track for batch install
217
- await update_package_json(repo, dev_updates, {
218
- strategy: options.version_strategy || 'caret',
219
- published_versions: published,
220
- log,
221
- git_ops: ops.git,
222
- });
223
- }
221
+ // Dev dep changes require deployment even without version bumps (rebuild needed).
222
+ // Sourced from the plan's dependency updates so the publisher derives nothing itself.
223
+ // Only package.json is rewritten + committed here — no install. These repos don't run
224
+ // `gro publish`; their `node_modules` is refreshed (and ETARGET-healed) by gro the next
225
+ // time they build/deploy/sync, so the executor never runs a bare `npm install` itself.
226
+ if (published.size > 0 && wetrun) {
227
+ const dev_updates_by_repo = group_dependency_updates(plan.dependency_updates, published, (update) => update.type === 'devDependencies');
228
+ if (dev_updates_by_repo.size > 0) {
229
+ log?.info(st('cyan', '\n🔄 Updating dev dependencies...\n'));
224
230
  }
225
- }
226
- // Phase 2b: Install dev dependencies for repos with dev dep updates
227
- if (wetrun && !options.skip_install && dev_updated_repos.size > 0) {
228
- log?.info(st('cyan', '\n📦 Installing dev dependencies for updated repos...\n'));
229
- for (const pkg_name of dev_updated_repos) {
230
- const repo = repos.find((r) => r.library.name === pkg_name);
231
+ for (const [repo_name, dev_updates] of dev_updates_by_repo) {
232
+ const repo = repo_by_name.get(repo_name);
231
233
  if (!repo)
232
234
  continue;
233
- try {
234
- log?.info(` Installing ${pkg_name}...`);
235
- await install_with_cache_healing(repo, ops, log);
236
- log?.info(st('green', ` ✅ Installed ${pkg_name}`));
237
- }
238
- catch (error) {
239
- const err = error instanceof Error ? error : new Error(String(error));
240
- failed.set(pkg_name, err);
241
- log?.error(st('red', ` ❌ Failed to install ${pkg_name}: ${err.message}`));
242
- // Continue with other installs instead of breaking
235
+ log?.info(` Updating ${dev_updates.size} dev dependencies in ${repo_name}`);
236
+ for (const [dep_name, dep_version] of dev_updates) {
237
+ emit({
238
+ event: 'dependency_updated',
239
+ dependent: repo_name,
240
+ dependency: dep_name,
241
+ version: dep_version,
242
+ dep_type: 'dev',
243
+ creates_changeset: false, // dev-dep updates redeploy without republishing
244
+ });
243
245
  }
246
+ changed_repos.add(repo_name); // Mark as changed for deployment
247
+ // No `published_versions` here on purpose: a dev-dep bump updates and commits
248
+ // package.json but must NOT generate a changeset — dev-only changes redeploy
249
+ // (rebuild) without republishing, so they shouldn't bump the next release.
250
+ await update_package_json(repo, dev_updates, {
251
+ strategy: options.version_strategy || 'caret',
252
+ log,
253
+ git_ops: ops.git,
254
+ fs_ops: ops.fs,
255
+ });
244
256
  }
245
257
  }
246
258
  // Phase 3: Deploy repos with changes (optional)
247
- // Deploys only repos that were: published, had prod/peer deps updated, or had dev deps updated
259
+ // Deploys only repos that were: published, had prod/peer deps updated, or had dev deps updated.
260
+ // Iterate `changed_repos` (insertion order) rather than `repos` order so deploys run in
261
+ // dependency order — and so the `--preview` side-effect list matches this exactly.
248
262
  if (options.deploy && wetrun) {
249
- const repos_to_deploy = repos.filter((r) => changed_repos.has(r.library.name));
263
+ const repos_to_deploy = Array.from(changed_repos)
264
+ .map((name) => repo_by_name.get(name))
265
+ .filter((r) => r !== undefined);
250
266
  log?.info(st('cyan', `\n🚢 Deploying ${repos_to_deploy.length}/${repos.length} repos with changes...\n`));
251
267
  for (const repo of repos_to_deploy) {
252
268
  try {
269
+ emit({ event: 'deploy_started', name: repo.library.name });
253
270
  log?.info(` Deploying ${repo.library.name}...`);
271
+ // Build fresh (no --no-build): a deployed site bundles its dependencies, so it
272
+ // must be rebuilt against the versions this run just published — the preflight
273
+ // build ran against the old versions, before the cascade rewrote package.json.
254
274
  const deploy_result = await ops.process.spawn({
255
275
  cmd: 'gro',
256
- args: ['deploy', '--no-build'],
276
+ args: ['deploy'],
257
277
  cwd: repo.repo_dir,
258
278
  });
259
279
  if (deploy_result.ok) {
280
+ emit({ event: 'deploy_completed', name: repo.library.name });
260
281
  log?.info(st('green', ` ✅ Deployed ${repo.library.name}`));
261
282
  }
262
283
  else {
284
+ emit({ event: 'deploy_failed', name: repo.library.name, error: deploy_result.message });
263
285
  log?.warn(st('yellow', ` ⚠️ Failed to deploy ${repo.library.name}`));
264
286
  }
265
287
  }
266
288
  catch (error) {
267
- log?.error(st('red', ` ❌ Error deploying ${repo.library.name}: ${error}`));
289
+ const err = error instanceof Error ? error : new Error(String(error));
290
+ emit({ event: 'deploy_failed', name: repo.library.name, error: err.message });
291
+ log?.error(st('red', ` ❌ Error deploying ${repo.library.name}: ${err.message}`));
268
292
  }
269
293
  }
270
294
  }
271
295
  // Summary
272
296
  const duration = Date.now() - start_time;
273
- const ok = failed.size === 0;
274
- log?.info(st('cyan', '\n📋 Publishing Summary\n'));
297
+ const ok = failed.size === 0 && plan.errors.length === 0;
298
+ const summary = summarize_events(capture.events, duration);
299
+ log?.info(st('cyan', `\n📋 ${wetrun ? 'Publishing' : 'Dry Run'} Summary\n`));
275
300
  log?.info(` Duration: ${(duration / 1000).toFixed(1)}s`);
276
- log?.info(` Published: ${published.size} packages`);
301
+ log?.info(` ${wetrun ? 'Published' : 'Would publish'}: ${published.size} packages`);
277
302
  if (failed.size > 0) {
278
303
  log?.info(` Failed: ${failed.size} packages`);
279
304
  }
305
+ // Surface plan diagnostics (a wetrun with errors threw above; this is mainly the dry run
306
+ // and non-blocking warnings) so an audit of the cascade sees them.
307
+ if (plan.warnings.length > 0) {
308
+ log?.warn(st('yellow', ` ⚠️ Plan warnings: ${plan.warnings.length}`));
309
+ for (const warning of plan.warnings)
310
+ log?.warn(st('yellow', ` - ${warning}`));
311
+ }
312
+ if (plan.errors.length > 0) {
313
+ log?.error(st('red', ` ❌ Plan errors: ${plan.errors.length}`));
314
+ for (const plan_error of plan.errors)
315
+ log?.error(st('red', ` - ${plan_error}`));
316
+ }
280
317
  if (ok) {
281
- log?.info(st('green', '\n✨ All packages published successfully!\n'));
318
+ if (wetrun) {
319
+ log?.info(st('green', '\n✨ All packages published successfully!\n'));
320
+ }
321
+ else {
322
+ log?.info(st('green', `\n✨ Dry run complete — ${published.size} package(s) would be published. Re-run with --wetrun to publish.`));
323
+ // The dry run is driven by the same plan as `gro gitops_plan`, so this
324
+ // count includes bump escalations and auto-generated changesets — it
325
+ // matches `gro gitops_plan` exactly (the full cascade).
326
+ log?.info(st('dim', 'This matches `gro gitops_plan` (the full cascade).\n'));
327
+ }
282
328
  }
283
329
  else {
284
- log?.error(st('red', '\n❌ Some packages failed to publish\n'));
330
+ log?.error(st('red', wetrun
331
+ ? '\n❌ Some packages failed to publish\n'
332
+ : '\n❌ Some packages failed during dry run\n'));
285
333
  }
334
+ emit({ event: 'run_finished', summary });
286
335
  return {
287
336
  ok,
288
337
  published: Array.from(published.values()),
289
338
  failed: Array.from(failed.entries()).map(([name, error]) => ({ name, error })),
290
339
  duration,
340
+ events: capture.events,
341
+ summary,
342
+ plan_errors: plan.errors,
343
+ plan_warnings: plan.warnings,
291
344
  };
292
345
  };
293
346
  /**
294
347
  * Publishes a single repo using `gro publish`.
295
348
  *
296
- * Dry run mode: Predicts version from changesets without side effects.
297
- * Real mode: Runs `gro publish --no-build` (builds already validated in preflight),
298
- * reads new version from `package.json`, and returns metadata.
349
+ * Dry run mode: reports the precomputed plan entry without side effects.
350
+ * Real mode: runs `gro publish --no-build` (builds already validated in preflight),
351
+ * reads the new version from `package.json`, and returns it alongside the plan's
352
+ * predicted bump metadata. The caller compares the read-back version to the plan to
353
+ * detect drift.
299
354
  *
300
- * @throws {Error} if changeset prediction fails (dry run) or publish fails (real)
355
+ * @throws {Error} if the publish, version read-back, or commit-hash lookup fails
301
356
  */
302
- const publish_single_repo = async (repo, options, ops = default_gitops_operations) => {
303
- const { wetrun, log } = options;
304
- const old_version = repo.library.package_json.version || '0.0.0';
357
+ const publish_single_repo = async (repo, options, ops, planned) => {
358
+ const { wetrun } = options;
305
359
  if (!wetrun) {
306
- // In dry run, predict version from changesets
307
- const prediction = await ops.changeset.predict_next_version({ repo, log });
308
- if (!prediction) {
309
- // No changesets found, skip this repo
310
- throw new Error(`No changesets found for ${repo.library.name}`);
311
- }
312
- if (!prediction.ok) {
313
- // Error reading changesets
314
- throw new Error(`Failed to predict version: ${prediction.message}`);
315
- }
316
- const { version: new_version, bump_type } = prediction;
317
- const breaking = is_breaking_change(old_version, bump_type);
360
+ // Dry run reports the precomputed plan — the single source of truth for the
361
+ // cascade (explicit changesets, bump escalations, and auto-generated changesets).
318
362
  return {
319
363
  name: repo.library.name,
320
- old_version,
321
- new_version,
322
- bump_type,
323
- breaking,
364
+ old_version: planned.from,
365
+ new_version: planned.to,
366
+ bump_type: planned.bump_type,
367
+ breaking: planned.breaking,
324
368
  commit: 'simulated',
325
- tag: `v${new_version}`,
369
+ tag: `v${planned.to}`,
326
370
  };
327
371
  }
328
372
  // Run gro publish with --no-build (builds were validated in preflight checks)
@@ -342,22 +386,52 @@ const publish_single_repo = async (repo, options, ops = default_gitops_operation
342
386
  }
343
387
  const package_json = JSON.parse(content_result.value);
344
388
  const new_version = package_json.version;
345
- // Determine bump type and if it's breaking
346
- const bump_type = detect_bump_type(old_version, new_version);
347
- const breaking = is_breaking_change(old_version, bump_type);
348
389
  // Get actual commit hash
349
390
  const commit_result = await ops.git.current_commit_hash({ cwd: repo.repo_dir });
350
391
  if (!commit_result.ok) {
351
392
  throw new Error(`Failed to get commit hash: ${commit_result.message}`);
352
393
  }
353
394
  const commit = commit_result.value;
395
+ // Bump metadata comes from the plan (the single source of truth); the caller
396
+ // fail-louds if `new_version` diverges from the plan's prediction.
354
397
  return {
355
398
  name: repo.library.name,
356
- old_version,
399
+ old_version: planned.from,
357
400
  new_version,
358
- bump_type,
359
- breaking,
401
+ bump_type: planned.bump_type,
402
+ breaking: planned.breaking,
360
403
  commit,
361
404
  tag: `v${new_version}`,
362
405
  };
363
406
  };
407
+ /**
408
+ * Groups dependency updates by dependent package — `dependent → (dependency → new
409
+ * version)`, the shape `update_package_json` consumes. Restricted by `predicate` (e.g.
410
+ * prod/peer for a given package, or all dev deps) and to dependencies that actually
411
+ * published this run, so a failed/aborted publish never propagates to its dependents.
412
+ */
413
+ export const group_dependency_updates = (updates, published, predicate) => {
414
+ const by_repo = new Map();
415
+ for (const update of updates) {
416
+ if (!predicate(update))
417
+ continue;
418
+ const published_dep = published.get(update.updated_dependency);
419
+ if (!published_dep)
420
+ continue;
421
+ let repo_updates = by_repo.get(update.dependent_package);
422
+ if (!repo_updates) {
423
+ repo_updates = new Map();
424
+ by_repo.set(update.dependent_package, repo_updates);
425
+ }
426
+ repo_updates.set(update.updated_dependency, published_dep.new_version);
427
+ }
428
+ return by_repo;
429
+ };
430
+ /** The dep_type tag for a prod/peer dependency-update event — `peer` if the edge is a peer
431
+ * dependency, else `prod`. Mirrors `derive_publish_steps`' classification so the executor's
432
+ * event stream and the preview agree. */
433
+ const dependency_update_type = (plan, dependent, dependency) => plan.dependency_updates.some((u) => u.dependent_package === dependent &&
434
+ u.updated_dependency === dependency &&
435
+ u.type === 'peerDependencies')
436
+ ? 'peer'
437
+ : 'prod';