nx 24.0.0 → 24.0.2

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 (51) hide show
  1. package/dist/src/ai/clone-ai-config-repo.js +49 -12
  2. package/dist/src/command-line/migrate/migrate-commits.d.ts +17 -7
  3. package/dist/src/command-line/migrate/migrate-commits.js +57 -17
  4. package/dist/src/command-line/migrate/run/clean-retry.js +4 -2
  5. package/dist/src/command-line/migrate/run/orchestrator.js +19 -13
  6. package/dist/src/daemon/client/client.d.ts +4 -0
  7. package/dist/src/daemon/client/client.js +67 -12
  8. package/dist/src/daemon/server/handle-process-in-background.js +21 -9
  9. package/dist/src/daemon/server/native-js-loader.d.ts +1 -0
  10. package/dist/src/daemon/server/native-js-loader.js +21 -0
  11. package/dist/src/daemon/server/project-graph-incremental-recomputation.js +4 -8
  12. package/dist/src/daemon/server/server.d.ts +2 -1
  13. package/dist/src/daemon/server/server.js +16 -3
  14. package/dist/src/daemon/server/start.d.ts +1 -0
  15. package/dist/src/daemon/server/start.js +2 -0
  16. package/dist/src/executors/run-commands/run-commands.impl.d.ts +1 -1
  17. package/dist/src/executors/run-commands/run-commands.impl.js +14 -8
  18. package/dist/src/executors/run-commands/running-tasks.d.ts +1 -1
  19. package/dist/src/executors/run-commands/running-tasks.js +126 -77
  20. package/dist/src/executors/run-commands/schema.json +1 -1
  21. package/dist/src/native/index.d.ts +1 -1
  22. package/dist/src/native/nx.wasm32-wasi.debug.wasm +0 -0
  23. package/dist/src/native/nx.wasm32-wasi.wasm +0 -0
  24. package/dist/src/plugins/js/lock-file/pnpm-parser.js +2 -1
  25. package/dist/src/tasks-runner/init-tasks-runner.js +103 -61
  26. package/dist/src/tasks-runner/life-cycles/static-run-many-terminal-output-life-cycle.js +5 -2
  27. package/dist/src/tasks-runner/life-cycles/static-run-one-terminal-output-life-cycle.js +4 -1
  28. package/dist/src/tasks-runner/life-cycles/summary-terminal-output-life-cycle.js +5 -1
  29. package/dist/src/tasks-runner/pseudo-terminal.d.ts +1 -1
  30. package/dist/src/tasks-runner/pseudo-terminal.js +2 -2
  31. package/dist/src/tasks-runner/readiness/probes.js +2 -2
  32. package/dist/src/tasks-runner/readiness/ready-when.d.ts +22 -1
  33. package/dist/src/tasks-runner/readiness/ready-when.js +25 -2
  34. package/dist/src/tasks-runner/run-command.d.ts +6 -2
  35. package/dist/src/tasks-runner/run-command.js +14 -25
  36. package/dist/src/tasks-runner/run-outcome.d.ts +16 -0
  37. package/dist/src/tasks-runner/run-outcome.js +39 -0
  38. package/dist/src/tasks-runner/running-tasks/running-task.d.ts +1 -1
  39. package/dist/src/tasks-runner/task-orchestrator.d.ts +4 -2
  40. package/dist/src/tasks-runner/task-orchestrator.js +92 -21
  41. package/dist/src/tasks-runner/tasks-schedule.js +4 -5
  42. package/dist/src/utils/child-process.js +1 -1
  43. package/dist/src/utils/find-matching-projects.js +9 -6
  44. package/dist/src/utils/git-utils.d.ts +6 -4
  45. package/dist/src/utils/git-utils.js +43 -6
  46. package/dist/src/utils/output.d.ts +4 -3
  47. package/dist/src/utils/output.js +4 -3
  48. package/dist/src/utils/package-manager.js +5 -0
  49. package/package.json +11 -11
  50. package/schemas/nx-schema.json +6 -0
  51. package/schemas/project-schema.json +6 -0
@@ -7,18 +7,59 @@ const os_1 = require("os");
7
7
  const path_1 = require("path");
8
8
  const REPO_URL = 'https://github.com/nrwl/nx-ai-agents-config';
9
9
  const CACHE_DIR = (0, path_1.join)((0, os_1.tmpdir)(), 'nx-ai-agents-config');
10
+ // `git rev-parse --local-env-vars`, plus GIT_NAMESPACE and the indexed
11
+ // GIT_CONFIG_KEY_<n> / GIT_CONFIG_VALUE_<n> pairs. Hooks export GIT_INDEX_FILE;
12
+ // inheriting it makes `git clone` rewrite the caller's index.
13
+ const GIT_LOCAL_REPO_ENV_VARS = new Set([
14
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
15
+ 'GIT_COMMON_DIR',
16
+ 'GIT_CONFIG',
17
+ 'GIT_CONFIG_COUNT',
18
+ 'GIT_CONFIG_PARAMETERS',
19
+ 'GIT_DIR',
20
+ 'GIT_GRAFT_FILE',
21
+ 'GIT_IMPLICIT_WORK_TREE',
22
+ 'GIT_INDEX_FILE',
23
+ 'GIT_NAMESPACE',
24
+ 'GIT_NO_REPLACE_OBJECTS',
25
+ 'GIT_OBJECT_DIRECTORY',
26
+ 'GIT_PREFIX',
27
+ 'GIT_REPLACE_REF_BASE',
28
+ 'GIT_SHALLOW_FILE',
29
+ 'GIT_WORK_TREE',
30
+ ]);
31
+ function isGitLocalRepoEnvVar(key) {
32
+ const upper = key.toUpperCase();
33
+ return (GIT_LOCAL_REPO_ENV_VARS.has(upper) ||
34
+ upper.startsWith('GIT_CONFIG_KEY_') ||
35
+ upper.startsWith('GIT_CONFIG_VALUE_'));
36
+ }
37
+ function environmentWithoutGitLocalRepoVars() {
38
+ const env = { ...process.env };
39
+ for (const key of Object.keys(env)) {
40
+ if (isGitLocalRepoEnvVar(key)) {
41
+ delete env[key];
42
+ }
43
+ }
44
+ return env;
45
+ }
46
+ function execGitWithoutLocalRepoEnv(command, timeout) {
47
+ return (0, child_process_1.execSync)(command, {
48
+ encoding: 'utf-8',
49
+ env: environmentWithoutGitLocalRepoVars(),
50
+ stdio: ['pipe', 'pipe', 'pipe'],
51
+ timeout,
52
+ windowsHide: true,
53
+ });
54
+ }
10
55
  /**
11
56
  * Get the latest commit hash from the remote repository.
12
57
  * Uses `git ls-remote` to fetch the HEAD commit hash without cloning.
13
58
  */
14
59
  function getLatestCommitHash() {
15
60
  try {
16
- const output = (0, child_process_1.execSync)(`git ls-remote ${REPO_URL} HEAD`, {
17
- encoding: 'utf-8',
18
- stdio: ['pipe', 'pipe', 'pipe'],
19
- timeout: 30000, // 30 second timeout
20
- windowsHide: true,
21
- });
61
+ const output = execGitWithoutLocalRepoEnv(`git ls-remote ${REPO_URL} HEAD`, 30000 // 30 second timeout
62
+ );
22
63
  const hash = output.split('\t')[0];
23
64
  if (!hash || hash.length < 10) {
24
65
  throw new Error('Invalid commit hash received');
@@ -43,12 +84,8 @@ function cloneRepo(targetPath) {
43
84
  if ((0, fs_1.existsSync)(tempPath)) {
44
85
  (0, fs_1.rmSync)(tempPath, { recursive: true, force: true });
45
86
  }
46
- (0, child_process_1.execSync)(`git clone --depth 1 ${REPO_URL} "${tempPath}"`, {
47
- encoding: 'utf-8',
48
- stdio: ['pipe', 'pipe', 'pipe'],
49
- timeout: 120000, // 2 minute timeout for clone
50
- windowsHide: true,
51
- });
87
+ execGitWithoutLocalRepoEnv(`git clone --depth 1 ${REPO_URL} "${tempPath}"`, 120000 // 2 minute timeout for clone
88
+ );
52
89
  // Remove .git directory after clone
53
90
  const gitDir = (0, path_1.join)(tempPath, '.git');
54
91
  if ((0, fs_1.existsSync)(gitDir)) {
@@ -1,5 +1,14 @@
1
+ import { type WorkingTreeStatus } from '../../utils/git-utils';
1
2
  import type { ResolvedAgentic } from './agentic/types';
2
3
  import { type MigrateOutputSink } from './deferred-output';
4
+ /** Workspace-relative paths nx migrate writes for itself. */
5
+ export declare const MIGRATE_OWNED_PATHS: string[];
6
+ /**
7
+ * The scratch state is excluded even when git ignores it, since its ignore
8
+ * rule can go missing mid-run.
9
+ */
10
+ export declare function migrateCommitExcludes(root: string): string[];
11
+ export declare function migrateTreeStatus(root: string): WorkingTreeStatus;
3
12
  /**
4
13
  * What becomes of a failed commit's changes: a later migration step's commit
5
14
  * takes them in, or, with no later step, the user commits or reverts them.
@@ -47,13 +56,14 @@ export declare function commitMigrationIfRequested(root: string, migration: {
47
56
  name: string;
48
57
  }>, recovery?: CommitFailureRecovery, sink?: MigrateOutputSink): Promise<CommitResult>;
49
58
  /**
50
- * Commits any pre-existing working-tree state into a dedicated "checkpoint"
51
- * commit before the first migration runs. Without this, the first migration's
52
- * commit would absorb whatever was already pending — most commonly the
53
- * package.json edit `nx migrate latest` produces and the lockfile churn from
54
- * the orchestrator's `npm install --ignore-scripts` step — and migration 1's
55
- * validation would see that mixed in with the generator output. No-op when
56
- * the working tree is already clean.
59
+ * Commits pre-existing working-tree state, except what `migrateCommitExcludes`
60
+ * leaves out, into a dedicated "checkpoint" commit before the first migration
61
+ * runs. Without this, the first migration's commit would absorb whatever was
62
+ * already pending (most commonly the package.json edit `nx migrate latest`
63
+ * produces and the lockfile churn from the orchestrator's
64
+ * `npm install --ignore-scripts` step), and migration 1's validation would see
65
+ * that mixed in with the generator output. No-op when the working tree is
66
+ * already clean.
57
67
  */
58
68
  export declare function commitCheckpointBeforeMigrations(root: string, commitPrefix: string): void;
59
69
  export declare function resolveCreateCommits(args: {
@@ -1,5 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MIGRATE_OWNED_PATHS = void 0;
4
+ exports.migrateCommitExcludes = migrateCommitExcludes;
5
+ exports.migrateTreeStatus = migrateTreeStatus;
3
6
  exports.commitMigrationIfRequested = commitMigrationIfRequested;
4
7
  exports.commitCheckpointBeforeMigrations = commitCheckpointBeforeMigrations;
5
8
  exports.resolveCreateCommits = resolveCreateCommits;
@@ -14,12 +17,44 @@ const git_utils_1 = require("../../utils/git-utils");
14
17
  const logger_1 = require("../../utils/logger");
15
18
  const output_1 = require("../../utils/output");
16
19
  const types_1 = require("./agentic/types");
20
+ const prompt_files_1 = require("./prompt-files");
17
21
  const safe_prompt_1 = require("./safe-prompt");
18
22
  const deferred_output_1 = require("./deferred-output");
19
- // `git add -A` captures an orchestrated run's scratch state whenever the
20
- // ignore rule that normally hides it goes missing mid-run (a checkout, a
21
- // .gitignore edit, or the migration's own changes).
22
- const MIGRATE_COMMIT_EXCLUDES = [types_1.MIGRATE_RUNS_RELATIVE_DIR];
23
+ const MIGRATE_PLAN_PATHS = ['migrations.json', prompt_files_1.AI_MIGRATIONS_DIR];
24
+ /** Workspace-relative paths nx migrate writes for itself. */
25
+ exports.MIGRATE_OWNED_PATHS = [
26
+ types_1.MIGRATE_RUNS_RELATIVE_DIR,
27
+ ...MIGRATE_PLAN_PATHS,
28
+ ];
29
+ /**
30
+ * The scratch state is excluded even when git ignores it, since its ignore
31
+ * rule can go missing mid-run.
32
+ */
33
+ function migrateCommitExcludes(root) {
34
+ return [
35
+ types_1.MIGRATE_RUNS_RELATIVE_DIR,
36
+ ...MIGRATE_PLAN_PATHS.filter((path) => isUncommitted(path, root)),
37
+ ];
38
+ }
39
+ function isUncommitted(path, root) {
40
+ const status = (0, git_utils_1.getPathHeadStatus)(path, root);
41
+ switch (status) {
42
+ case 'absent':
43
+ return true;
44
+ // On a failed probe the path stays visible, so clean-tree checks err
45
+ // toward dirty.
46
+ case 'committed':
47
+ case 'unknown':
48
+ return false;
49
+ default: {
50
+ const unhandled = status;
51
+ throw new Error(`Unhandled path HEAD status: ${unhandled}`);
52
+ }
53
+ }
54
+ }
55
+ function migrateTreeStatus(root) {
56
+ return (0, git_utils_1.getWorkingTreeStatus)(root, migrateCommitExcludes(root));
57
+ }
23
58
  const AGENT_SESSION_NO_INPUT = "Commits in this session cannot ask for input, such as a signing passphrase or a hook's prompt";
24
59
  function commitFailureGuidance(recovery, inAgentSession) {
25
60
  switch (recovery) {
@@ -56,16 +91,19 @@ async function commitMigrationIfRequested(root, migration, shouldCreateCommits,
56
91
  return { status: 'disabled' };
57
92
  const out = sink ?? deferred_output_1.terminalOutput;
58
93
  await installDepsIfChanged();
59
- // Generator may have only touched gitignored paths or the excluded scratch
60
- // dir, or the prompt half made no change: log neutrally, not as an error.
94
+ // Generator may have only touched gitignored paths or the excluded owned
95
+ // paths, or the prompt half made no change: log neutrally, not as an error.
61
96
  // The probe excludes what the commit excludes, else the commit fails empty.
62
- if (!(0, git_utils_1.hasUncommittedChanges)(root, MIGRATE_COMMIT_EXCLUDES)) {
97
+ const excludes = migrateCommitExcludes(root);
98
+ if (!(0, git_utils_1.hasUncommittedChanges)(root, excludes)) {
63
99
  out.line('dim', `- No changes to commit for ${migration.name}.`);
64
100
  return { status: 'no-changes' };
65
101
  }
66
102
  const commitMessage = buildCommitMessage(`${commitPrefix}${migration.name}`, pendingMigrations);
67
103
  try {
68
- const sha = await (0, git_utils_1.tryCommitChangesAsync)(commitMessage, root, MIGRATE_COMMIT_EXCLUDES, { withoutTerminal: sink !== undefined });
104
+ const sha = await (0, git_utils_1.tryCommitChangesAsync)(commitMessage, root, excludes, {
105
+ withoutTerminal: sink !== undefined,
106
+ });
69
107
  if (sha)
70
108
  return { status: 'committed', sha };
71
109
  // null = commit landed but `git rev-parse HEAD` failed (see
@@ -99,19 +137,21 @@ function buildCommitMessage(subject, pendingMigrations) {
99
137
  return lines.join('\n');
100
138
  }
101
139
  /**
102
- * Commits any pre-existing working-tree state into a dedicated "checkpoint"
103
- * commit before the first migration runs. Without this, the first migration's
104
- * commit would absorb whatever was already pending — most commonly the
105
- * package.json edit `nx migrate latest` produces and the lockfile churn from
106
- * the orchestrator's `npm install --ignore-scripts` step — and migration 1's
107
- * validation would see that mixed in with the generator output. No-op when
108
- * the working tree is already clean.
140
+ * Commits pre-existing working-tree state, except what `migrateCommitExcludes`
141
+ * leaves out, into a dedicated "checkpoint" commit before the first migration
142
+ * runs. Without this, the first migration's commit would absorb whatever was
143
+ * already pending (most commonly the package.json edit `nx migrate latest`
144
+ * produces and the lockfile churn from the orchestrator's
145
+ * `npm install --ignore-scripts` step), and migration 1's validation would see
146
+ * that mixed in with the generator output. No-op when the working tree is
147
+ * already clean.
109
148
  */
110
149
  function commitCheckpointBeforeMigrations(root, commitPrefix) {
111
- if (!(0, git_utils_1.hasUncommittedChanges)(root, MIGRATE_COMMIT_EXCLUDES))
150
+ const excludes = migrateCommitExcludes(root);
151
+ if (!(0, git_utils_1.hasUncommittedChanges)(root, excludes))
112
152
  return;
113
153
  try {
114
- const sha = (0, git_utils_1.tryCommitChanges)(`${commitPrefix}checkpoint before running migrations`, root, MIGRATE_COMMIT_EXCLUDES);
154
+ const sha = (0, git_utils_1.tryCommitChanges)(`${commitPrefix}checkpoint before running migrations`, root, excludes);
115
155
  if (sha) {
116
156
  logger_1.logger.info(pc.dim(`- Checkpoint commit created: ${sha}`));
117
157
  return;
@@ -4,7 +4,7 @@ exports.canOfferCleanRetry = canOfferCleanRetry;
4
4
  exports.cleanRetryUnavailableReason = cleanRetryUnavailableReason;
5
5
  exports.resetForCleanRetry = resetForCleanRetry;
6
6
  const git_utils_1 = require("../../../utils/git-utils");
7
- const types_1 = require("../agentic/types");
7
+ const migrate_commits_1 = require("../migrate-commits");
8
8
  const agent_output_1 = require("./agent-output");
9
9
  const issues_1 = require("./issues");
10
10
  const state_lock_1 = require("./state-lock");
@@ -95,5 +95,7 @@ function resetForCleanRetry(root, dir, stepId) {
95
95
  return reopened.state;
96
96
  });
97
97
  archiveReopenedResolutions(dir, prepared, updates, (0, state_machine_1.stepLabel)(step));
98
- (0, git_utils_1.resetWorkingTree)(step.gitRefBefore, [types_1.MIGRATE_RUNS_RELATIVE_DIR], root);
98
+ // Unlike the commit exclusions, every owned path, committed or not: a failed
99
+ // probe must not let the reset remove the plan or prompt files.
100
+ (0, git_utils_1.resetWorkingTree)(step.gitRefBefore, migrate_commits_1.MIGRATE_OWNED_PATHS, root);
99
101
  }
@@ -233,7 +233,7 @@ async function runOrchestratorInit(input) {
233
233
  // step's gitRefBefore and rules out clean retries for the whole run. A
234
234
  // failed probe counts as dirty: mistaking it for clean would let a later
235
235
  // retry-clean reset destroy the very work this flag exists to protect.
236
- const checkpointFailed = createCommits && (0, git_utils_1.getWorkingTreeStatus)(root) !== 'clean';
236
+ const checkpointFailed = createCommits && (0, migrate_commits_1.migrateTreeStatus)(root) !== 'clean';
237
237
  const branch = (0, git_utils_1.getGitCurrentBranch)(root);
238
238
  const state = {
239
239
  formatVersion: run_state_1.CURRENT_RUN_STATE_FORMAT_VERSION,
@@ -687,7 +687,7 @@ function ensureCheckpoint(root, dir, state) {
687
687
  // The retried checkpoint captured everything, so clean retries are safe
688
688
  // again. Only a verified-clean tree clears the flag: a failed probe proves
689
689
  // nothing was captured.
690
- const cleared = (0, git_utils_1.getWorkingTreeStatus)(root) === 'clean';
690
+ const cleared = (0, migrate_commits_1.migrateTreeStatus)(root) === 'clean';
691
691
  if (!checkpoint && !cleared)
692
692
  return state;
693
693
  return (0, state_lock_1.updateRunState)(dir, (fresh) => {
@@ -717,7 +717,7 @@ function ensureCheckpoint(root, dir, state) {
717
717
  function checkpointEntry(root, commitPrefix, before) {
718
718
  // Skip only on a verified-clean tree; on a failed probe the commit attempt
719
719
  // below re-probes and may succeed once the transient failure passes.
720
- if ((0, git_utils_1.getWorkingTreeStatus)(root) === 'clean') {
720
+ if ((0, migrate_commits_1.migrateTreeStatus)(root) === 'clean') {
721
721
  return null;
722
722
  }
723
723
  (0, migrate_commits_1.commitCheckpointBeforeMigrations)(root, commitPrefix);
@@ -1282,7 +1282,7 @@ async function foldLedgerEntry(root, dir, state, step, promptOutcome, scope) {
1282
1282
  // is not verifiably clean (see foldLedgerEntry for why).
1283
1283
  async function retainedTreeSideEffects(root, dir, state, step, seam, scope) {
1284
1284
  const installFailed = await installFailedForStep(root, dir, state, step, seam, scope);
1285
- const entry = state.createCommits && (0, git_utils_1.getWorkingTreeStatus)(root) !== 'clean'
1285
+ const entry = state.createCommits && (0, migrate_commits_1.migrateTreeStatus)(root) !== 'clean'
1286
1286
  ? { kind: 'failed', stepIds: [step.id] }
1287
1287
  : null;
1288
1288
  return { entry, installFailed };
@@ -1419,7 +1419,7 @@ async function applyReconcileStepAction(root, dir, state, action, scope) {
1419
1419
  // Only the tree can say whether the reset left it clean. Anything else is
1420
1420
  // refused: accepting would rearm a step whose next attempt reruns the
1421
1421
  // generator over the previous attempt's output.
1422
- if ((0, git_utils_1.getWorkingTreeStatus)(root) !== 'clean') {
1422
+ if ((0, migrate_commits_1.migrateTreeStatus)(root) !== 'clean') {
1423
1423
  return {
1424
1424
  kind: 'error',
1425
1425
  reason: `Cannot apply action 'retry-clean' to step '${step.id}': the working tree is not verifiably clean after the reset to ${step.gitRefBefore}. Inspect it with \`git status\`, then re-run it. ${fallback}`,
@@ -1448,7 +1448,7 @@ async function applyReconcileStepAction(root, dir, state, action, scope) {
1448
1448
  reason: `Cannot apply action 'unresolved' to step '${step.id}': the reset to ${step.gitRefBefore} failed: ${e instanceof Error ? e.message : String(e)}`,
1449
1449
  };
1450
1450
  }
1451
- if ((0, git_utils_1.getWorkingTreeStatus)(root) !== 'clean') {
1451
+ if ((0, migrate_commits_1.migrateTreeStatus)(root) !== 'clean') {
1452
1452
  return {
1453
1453
  kind: 'error',
1454
1454
  reason: `Cannot apply action 'unresolved' to step '${step.id}': the working tree is not verifiably clean after the reset to ${step.gitRefBefore}. Inspect it with \`git status\`, then re-run it.`,
@@ -1744,7 +1744,7 @@ function dispenseNextStep(root, dir, runId, state, step, noProgress) {
1744
1744
  function readDispenseBaselines(root) {
1745
1745
  return {
1746
1746
  gitRefBefore: (0, git_utils_1.getLatestCommitSha)(root) ?? undefined,
1747
- treeCleanAtDispense: (0, git_utils_1.getWorkingTreeStatus)(root) === 'clean',
1747
+ treeCleanAtDispense: (0, migrate_commits_1.migrateTreeStatus)(root) === 'clean',
1748
1748
  depsHashAtDispense: (0, util_1.depsHash)(root),
1749
1749
  };
1750
1750
  }
@@ -1847,7 +1847,7 @@ function emitRetryFailed(root, runId, state, step, noProgress) {
1847
1847
  : [retryOptionLine(retrySafety, reconcileCommand(root, runId, 'retry'))]),
1848
1848
  ];
1849
1849
  if (cleanRetry && !capReached) {
1850
- lines.push(` retry-clean: reset the tree to ${step.gitRefBefore ?? 'the pre-migration ref'} (discarding its uncommitted tracked changes and the untracked files git does not ignore, ${types_1.MIGRATE_RUNS_RELATIVE_DIR} kept) and retry from that clean state by running: ${reconcileCommand(root, runId, 'retry-clean')}`);
1850
+ lines.push(` retry-clean: reset the tree to ${step.gitRefBefore ?? 'the pre-migration ref'} (discarding its uncommitted tracked changes and the untracked files git does not ignore, keeping ${KEPT_OWNED_PATHS}) and retry from that clean state by running: ${reconcileCommand(root, runId, 'retry-clean')}`);
1851
1851
  }
1852
1852
  // A failed commit is already named above the choices.
1853
1853
  const adoptWhen = recordedCommitFailed(state, step)
@@ -1966,7 +1966,7 @@ function assessPreMarkerRetry(root, step) {
1966
1966
  reason: `HEAD is at ${head ?? '(unreadable)'} rather than the ${step.gitRefBefore ?? '(unrecorded)'} this migration started from, so the failed attempt's changes may already be committed and rerunning the generator could apply them twice.`,
1967
1967
  };
1968
1968
  }
1969
- if ((0, git_utils_1.getWorkingTreeStatus)(root) !== 'clean') {
1969
+ if ((0, migrate_commits_1.migrateTreeStatus)(root) !== 'clean') {
1970
1970
  return {
1971
1971
  kind: 'unsafe',
1972
1972
  reason: `the working tree is not verifiably clean, and the failed attempt may have written to it before failing; rerunning the generator over those changes could apply them twice.`,
@@ -1988,7 +1988,7 @@ function unresolvedOptionLine(root, runId, state, step, resetTree) {
1988
1988
  : `The failure is recorded as a run issue and listed in the completion report.`;
1989
1989
  const noun = (0, state_machine_1.stepNoun)(step);
1990
1990
  if (resetTree) {
1991
- return ` unresolved: give up on this ${noun}, resetting the tree to ${step.gitRefBefore ?? 'the pre-migration ref'} (discarding what the failed attempt left, ${types_1.MIGRATE_RUNS_RELATIVE_DIR} kept), then run: ${command}. ${recorded}`;
1991
+ return ` unresolved: give up on this ${noun}, resetting the tree to ${step.gitRefBefore ?? 'the pre-migration ref'} (discarding what the failed attempt left, keeping ${KEPT_OWNED_PATHS}), then run: ${command}. ${recorded}`;
1992
1992
  }
1993
1993
  if (state.createCommits) {
1994
1994
  return ` unresolved: give up on this ${noun}; its partial changes are committed under its name, marked unresolved, and the run moves on. Then run: ${command}. ${recorded}`;
@@ -2019,7 +2019,7 @@ function emitDied(root, runId, state, step, noProgress) {
2019
2019
  options.push(` retry: keep everything this migration already produced (its commit, if any, and the current tree) and run only the part that did not complete, then run: ${reconcileCommand(root, runId, 'retry')}`);
2020
2020
  }
2021
2021
  if (cleanRetry && !capReached) {
2022
- options.push(` retry-clean: reset the tree to ${ref ?? 'the pre-migration ref'} (discarding its uncommitted tracked changes and the untracked files git does not ignore, ${types_1.MIGRATE_RUNS_RELATIVE_DIR} kept) and retry from that clean state by running: ${reconcileCommand(root, runId, 'retry-clean')}`);
2022
+ options.push(` retry-clean: reset the tree to ${ref ?? 'the pre-migration ref'} (discarding its uncommitted tracked changes and the untracked files git does not ignore, keeping ${KEPT_OWNED_PATHS}) and retry from that clean state by running: ${reconcileCommand(root, runId, 'retry-clean')}`);
2023
2023
  }
2024
2024
  else if (!capReached) {
2025
2025
  lines.push(`A clean retry is unavailable: ${(0, clean_retry_1.cleanRetryUnavailableReason)(root, state, step, head)}`);
@@ -2321,7 +2321,7 @@ function completionWarnings(root, runId, state) {
2321
2321
  // tree can still be unrelated edits, so the warning only claims the changes
2322
2322
  // "may remain".
2323
2323
  const debtStepIds = (0, state_machine_1.uncoveredFailedStepIds)(state);
2324
- const uncommitted = debtStepIds.length > 0 && (0, git_utils_1.getWorkingTreeStatus)(root) !== 'clean'
2324
+ const uncommitted = debtStepIds.length > 0 && (0, migrate_commits_1.migrateTreeStatus)(root) !== 'clean'
2325
2325
  ? state.steps.filter((s) => debtStepIds.includes(s.id))
2326
2326
  : [];
2327
2327
  const uninstalled = state.steps.filter((s) => s.installFailed);
@@ -2512,12 +2512,18 @@ function removeHandoff(dir, stepId) {
2512
2512
  (0, fs_1.rmSync)((0, handoff_1.runStepHandoffPath)(dir, stepId), { force: true });
2513
2513
  }
2514
2514
  }
2515
+ const KEPT_OWNED_PATHS = `${migrate_commits_1.MIGRATE_OWNED_PATHS.slice(0, -1).join(', ')} and ${migrate_commits_1.MIGRATE_OWNED_PATHS[migrate_commits_1.MIGRATE_OWNED_PATHS.length - 1]}`;
2515
2516
  // null means the probe itself failed; the death dispense renders that as
2516
2517
  // '(unknown)', because '(clean)' would invite a retry-clean reset over
2517
2518
  // evidence that was never gathered (getWorkingTreeStatus's contract).
2518
2519
  function dirtyTreeSummary(root) {
2519
2520
  try {
2520
- return (0, child_process_1.execSync)('git status --porcelain', {
2521
+ return (0, child_process_1.execFileSync)('git', [
2522
+ 'status',
2523
+ '--porcelain',
2524
+ '--',
2525
+ ...(0, migrate_commits_1.migrateCommitExcludes)(root).map((path) => `:(exclude)${path}`),
2526
+ ], {
2521
2527
  encoding: 'utf8',
2522
2528
  cwd: root,
2523
2529
  stdio: ['ignore', 'pipe', 'pipe'],
@@ -53,6 +53,7 @@ export declare class DaemonClient {
53
53
  private fileWatcherMessenger;
54
54
  private fileWatcherReconnecting;
55
55
  private fileWatcherFramingFailures;
56
+ private fileWatcherRegistrations;
56
57
  private fileWatcherCallbacks;
57
58
  private fileWatcherConfigs;
58
59
  private projectGraphListenerMessenger;
@@ -81,6 +82,9 @@ export declare class DaemonClient {
81
82
  changedProjects: string[];
82
83
  changedFiles: ChangedFile[];
83
84
  } | null) => void): Promise<UnregisterCallback>;
85
+ private sendFileWatcherRegistration;
86
+ private handleFileWatcherRegistration;
87
+ private rejectFileWatcherRegistrations;
84
88
  private reconnectFileWatcher;
85
89
  registerProjectGraphRecomputationListener(callback: (error: Error | null | 'reconnecting' | 'reconnected' | 'closed', data: {
86
90
  projectGraph: ProjectGraph;
@@ -100,6 +100,7 @@ class DaemonClient {
100
100
  this._pluginWorkerConnectionLost = null;
101
101
  this.fileWatcherReconnecting = false;
102
102
  this.fileWatcherFramingFailures = 0;
103
+ this.fileWatcherRegistrations = new Map();
103
104
  this.fileWatcherCallbacks = new Map();
104
105
  this.fileWatcherConfigs = new Map();
105
106
  this.projectGraphListenerReconnecting = false;
@@ -156,6 +157,7 @@ class DaemonClient {
156
157
  return this._enabled;
157
158
  }
158
159
  reset() {
160
+ this.rejectFileWatcherRegistrations(new Error('Daemon client reset'));
159
161
  this.socketMessenger?.close();
160
162
  this.socketMessenger = null;
161
163
  this.queue = new promised_based_queue_1.PromisedBasedQueue();
@@ -263,16 +265,15 @@ class DaemonClient {
263
265
  }
264
266
  // Generate unique ID for this callback
265
267
  const callbackId = Math.random().toString(36).substring(2, 11);
266
- // Store callback and config for reconnection
267
- this.fileWatcherCallbacks.set(callbackId, callback);
268
- this.fileWatcherConfigs.set(callbackId, config);
269
- await this.queue.sendToQueue(async () => {
268
+ await this.queue
269
+ .sendToQueue(async () => {
270
+ // Only registrations whose queue entry has started belong to this
271
+ // connection. A failed earlier entry must not reconnect a queued one.
272
+ this.fileWatcherCallbacks.set(callbackId, callback);
273
+ this.fileWatcherConfigs.set(callbackId, config);
270
274
  // If we already have a connection, just register the new config
271
275
  if (this.fileWatcherMessenger) {
272
- this.fileWatcherMessenger.sendMessage({
273
- type: 'REGISTER_FILE_WATCHER',
274
- config,
275
- });
276
+ await this.sendFileWatcherRegistration(callbackId);
276
277
  return;
277
278
  }
278
279
  await this.startDaemonIfNecessary();
@@ -280,6 +281,8 @@ class DaemonClient {
280
281
  this.fileWatcherMessenger = new daemon_socket_messenger_1.DaemonSocketMessenger((0, net_1.connect)(socketPath)).listen((message) => {
281
282
  try {
282
283
  const parsedMessage = (0, consume_messages_from_socket_1.parseMessage)(message);
284
+ if (this.handleFileWatcherRegistration(parsedMessage))
285
+ return;
283
286
  // A delivered message means the stream is healthy again.
284
287
  this.fileWatcherFramingFailures = 0;
285
288
  if (parsedMessage?.watcherError) {
@@ -303,6 +306,7 @@ class DaemonClient {
303
306
  // Connection closed - trigger reconnection
304
307
  logger_1.clientLogger.log(`[FileWatcher] Socket closed, triggering reconnection`);
305
308
  this.fileWatcherMessenger = undefined;
309
+ this.rejectFileWatcherRegistrations(new Error('Daemon disconnected before watcher registration completed'));
306
310
  for (const cb of this.fileWatcherCallbacks.values()) {
307
311
  cb('reconnecting', null);
308
312
  }
@@ -324,10 +328,12 @@ class DaemonClient {
324
328
  // failure would otherwise leave this channel silent forever.
325
329
  this.fileWatcherMessenger?.close();
326
330
  });
327
- this.fileWatcherMessenger.sendMessage({
328
- type: 'REGISTER_FILE_WATCHER',
329
- config,
330
- });
331
+ await this.sendFileWatcherRegistration(callbackId);
332
+ })
333
+ .catch((error) => {
334
+ this.fileWatcherCallbacks.delete(callbackId);
335
+ this.fileWatcherConfigs.delete(callbackId);
336
+ throw error;
331
337
  });
332
338
  // Return unregister function
333
339
  return () => {
@@ -340,6 +346,52 @@ class DaemonClient {
340
346
  }
341
347
  };
342
348
  }
349
+ sendFileWatcherRegistration(callbackId) {
350
+ return new Promise((resolve, reject) => {
351
+ const cleanup = () => {
352
+ clearTimeout(timeout);
353
+ this.fileWatcherRegistrations.delete(callbackId);
354
+ };
355
+ const fail = (error) => {
356
+ cleanup();
357
+ this.fileWatcherCallbacks.delete(callbackId);
358
+ this.fileWatcherConfigs.delete(callbackId);
359
+ reject(error);
360
+ if (this.fileWatcherCallbacks.size === 0) {
361
+ this.fileWatcherMessenger?.close();
362
+ }
363
+ };
364
+ const timeout = setTimeout(() => fail(new Error('Timed out waiting for daemon watcher registration')), WAIT_FOR_SERVER_CONFIG.maxAttempts * WAIT_FOR_SERVER_CONFIG.delayMs);
365
+ this.fileWatcherRegistrations.set(callbackId, {
366
+ resolve: () => {
367
+ cleanup();
368
+ resolve();
369
+ },
370
+ reject: fail,
371
+ });
372
+ try {
373
+ this.fileWatcherMessenger.sendMessage({
374
+ type: 'REGISTER_FILE_WATCHER',
375
+ config: this.fileWatcherConfigs.get(callbackId),
376
+ registrationId: callbackId,
377
+ });
378
+ }
379
+ catch (error) {
380
+ fail(error);
381
+ }
382
+ });
383
+ }
384
+ handleFileWatcherRegistration(message) {
385
+ if (message?.type !== 'FILE_WATCHER_REGISTERED')
386
+ return false;
387
+ this.fileWatcherRegistrations.get(message.registrationId)?.resolve();
388
+ return true;
389
+ }
390
+ rejectFileWatcherRegistrations(error) {
391
+ for (const registration of [...this.fileWatcherRegistrations.values()]) {
392
+ registration.reject(error);
393
+ }
394
+ }
343
395
  async reconnectFileWatcher() {
344
396
  // Guard against concurrent reconnection attempts
345
397
  if (this.fileWatcherReconnecting) {
@@ -394,6 +446,8 @@ class DaemonClient {
394
446
  this.fileWatcherMessenger = new daemon_socket_messenger_1.DaemonSocketMessenger((0, net_1.connect)(socketPath)).listen((message) => {
395
447
  try {
396
448
  const parsedMessage = (0, consume_messages_from_socket_1.parseMessage)(message);
449
+ if (this.handleFileWatcherRegistration(parsedMessage))
450
+ return;
397
451
  // A delivered message means the stream is healthy again.
398
452
  this.fileWatcherFramingFailures = 0;
399
453
  for (const cb of this.fileWatcherCallbacks.values()) {
@@ -408,6 +462,7 @@ class DaemonClient {
408
462
  }, () => {
409
463
  // Connection closed - trigger reconnection again
410
464
  this.fileWatcherMessenger = undefined;
465
+ this.rejectFileWatcherRegistrations(new Error('Daemon disconnected before watcher registration completed'));
411
466
  // Reset reconnection flag before triggering reconnection
412
467
  this.fileWatcherReconnecting = false;
413
468
  for (const cb of this.fileWatcherCallbacks.values()) {
@@ -3,18 +3,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.handleProcessInBackground = handleProcessInBackground;
4
4
  const logger_1 = require("../logger");
5
5
  const installation_directory_1 = require("../../utils/installation-directory");
6
+ const socket_utils_1 = require("../socket-utils");
7
+ const native_js_loader_1 = require("./native-js-loader");
6
8
  async function handleProcessInBackground(payload) {
7
9
  let fn;
8
10
  try {
9
- fn = require(require.resolve(payload.requirePath, {
11
+ fn = (0, native_js_loader_1.requireWithNativeJsLoader)(require.resolve(payload.requirePath, {
10
12
  paths: (0, installation_directory_1.getNxRequirePaths)(),
11
13
  })).default;
12
14
  }
13
15
  catch (e) {
14
- return {
15
- description: `Unable to require ${payload.requirePath}`,
16
- error: new Error(`Unable to require ${payload.requirePath}`),
17
- };
16
+ const description = `Unable to require ${payload.requirePath}`;
17
+ return { description, error: toTransportableError(e, description) };
18
18
  }
19
19
  try {
20
20
  const response = await fn(payload.data, logger_1.serverLogger);
@@ -24,9 +24,21 @@ async function handleProcessInBackground(payload) {
24
24
  };
25
25
  }
26
26
  catch (e) {
27
- return {
28
- description: `Error when processing ${payload.type}.`,
29
- error: e,
30
- };
27
+ const description = `Error when processing ${payload.type}.`;
28
+ return { description, error: toTransportableError(e, description) };
29
+ }
30
+ }
31
+ function toTransportableError(e, fallbackMessage) {
32
+ if (!(e instanceof Error)) {
33
+ return new Error(fallbackMessage);
34
+ }
35
+ try {
36
+ (0, socket_utils_1.serializeResult)(e, null, null);
37
+ return e;
38
+ }
39
+ catch {
40
+ const copy = new Error(e.message);
41
+ copy.stack = e.stack;
42
+ return copy;
31
43
  }
32
44
  }
@@ -0,0 +1 @@
1
+ export declare function requireWithNativeJsLoader(path: string): any;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requireWithNativeJsLoader = requireWithNativeJsLoader;
4
+ // Captured when the daemon starts, before plugins or sync generators can
5
+ // replace it (e.g. @swc-node/register compiles every .js outside node_modules).
6
+ const nativeJsLoader = require.extensions?.['.js'];
7
+ function requireWithNativeJsLoader(path) {
8
+ // Undefined when a loader hook (e.g. Yarn PnP's) has Node's ESM loader run
9
+ // nx's CommonJS. The require nx gets there never runs .js hooks.
10
+ if (!nativeJsLoader) {
11
+ return require(path);
12
+ }
13
+ const currentJsLoader = require.extensions['.js'];
14
+ require.extensions['.js'] = nativeJsLoader;
15
+ try {
16
+ return require(path);
17
+ }
18
+ finally {
19
+ require.extensions['.js'] = currentJsLoader;
20
+ }
21
+ }