@memnexus-ai/mx-agent-cli 0.1.303 → 0.1.305

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 (159) hide show
  1. package/dist/agent-config/.mx-config-generation.json +2 -2
  2. package/dist/agent-config/AGENTS.md.template +1 -1
  3. package/dist/agent-config/agents/bar-raiser.md +41 -1
  4. package/dist/agent-config/agents/git-expert.md +58 -54
  5. package/dist/agent-config/claude-md/CLAUDE.core.md +1 -1
  6. package/dist/agent-config/hooks/session-idle-gate.sh +14 -1
  7. package/dist/agent-config/hooks/subagent-write-guard.sh +198 -12
  8. package/dist/agent-config/hooks/worktree-guard.sh +8 -6
  9. package/dist/agent-config/skills/mx-post-merge-sync/SKILL.md +59 -51
  10. package/dist/commands/codex-agent-gate.d.ts +1 -2
  11. package/dist/commands/codex-agent-gate.d.ts.map +1 -1
  12. package/dist/commands/codex-agent-gate.js +1 -2
  13. package/dist/commands/codex-agent-gate.js.map +1 -1
  14. package/dist/commands/codex-deploy-config.d.ts +6 -0
  15. package/dist/commands/codex-deploy-config.d.ts.map +1 -1
  16. package/dist/commands/codex-deploy-config.js +28 -8
  17. package/dist/commands/codex-deploy-config.js.map +1 -1
  18. package/dist/commands/codex-prove-guards.d.ts +2 -0
  19. package/dist/commands/codex-prove-guards.d.ts.map +1 -1
  20. package/dist/commands/codex-prove-guards.js +31 -3
  21. package/dist/commands/codex-prove-guards.js.map +1 -1
  22. package/dist/commands/codex-trust-keys.d.ts +2 -0
  23. package/dist/commands/codex-trust-keys.d.ts.map +1 -1
  24. package/dist/commands/codex-trust-keys.js +27 -7
  25. package/dist/commands/codex-trust-keys.js.map +1 -1
  26. package/dist/commands/coordination.d.ts +16 -0
  27. package/dist/commands/coordination.d.ts.map +1 -1
  28. package/dist/commands/coordination.js +24 -2
  29. package/dist/commands/coordination.js.map +1 -1
  30. package/dist/commands/create.d.ts +164 -7
  31. package/dist/commands/create.d.ts.map +1 -1
  32. package/dist/commands/create.js +293 -91
  33. package/dist/commands/create.js.map +1 -1
  34. package/dist/commands/doctor.d.ts +17 -0
  35. package/dist/commands/doctor.d.ts.map +1 -1
  36. package/dist/commands/doctor.js +33 -0
  37. package/dist/commands/doctor.js.map +1 -1
  38. package/dist/commands/gh.d.ts +3 -2
  39. package/dist/commands/gh.d.ts.map +1 -1
  40. package/dist/commands/gh.js +3 -2
  41. package/dist/commands/gh.js.map +1 -1
  42. package/dist/commands/new.d.ts +132 -17
  43. package/dist/commands/new.d.ts.map +1 -1
  44. package/dist/commands/new.js +426 -74
  45. package/dist/commands/new.js.map +1 -1
  46. package/dist/commands/start.d.ts +6 -0
  47. package/dist/commands/start.d.ts.map +1 -1
  48. package/dist/commands/start.js +105 -17
  49. package/dist/commands/start.js.map +1 -1
  50. package/dist/commands/status.d.ts +7 -0
  51. package/dist/commands/status.d.ts.map +1 -1
  52. package/dist/commands/status.js +21 -1
  53. package/dist/commands/status.js.map +1 -1
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +28 -4
  56. package/dist/index.js.map +1 -1
  57. package/dist/lib/agent-session.d.ts +11 -0
  58. package/dist/lib/agent-session.d.ts.map +1 -1
  59. package/dist/lib/agent-session.js +26 -7
  60. package/dist/lib/agent-session.js.map +1 -1
  61. package/dist/lib/behavioral-injection.d.ts.map +1 -1
  62. package/dist/lib/behavioral-injection.js +25 -7
  63. package/dist/lib/behavioral-injection.js.map +1 -1
  64. package/dist/lib/catalog-commit.d.ts.map +1 -1
  65. package/dist/lib/catalog-commit.js +17 -14
  66. package/dist/lib/catalog-commit.js.map +1 -1
  67. package/dist/lib/catalog.d.ts +93 -2
  68. package/dist/lib/catalog.d.ts.map +1 -1
  69. package/dist/lib/catalog.js +116 -9
  70. package/dist/lib/catalog.js.map +1 -1
  71. package/dist/lib/claude.d.ts.map +1 -1
  72. package/dist/lib/claude.js +28 -4
  73. package/dist/lib/claude.js.map +1 -1
  74. package/dist/lib/fleet-data.d.ts +98 -9
  75. package/dist/lib/fleet-data.d.ts.map +1 -1
  76. package/dist/lib/fleet-data.js +353 -34
  77. package/dist/lib/fleet-data.js.map +1 -1
  78. package/dist/lib/fleet-render.d.ts +8 -1
  79. package/dist/lib/fleet-render.d.ts.map +1 -1
  80. package/dist/lib/fleet-render.js +10 -3
  81. package/dist/lib/fleet-render.js.map +1 -1
  82. package/dist/lib/gh-remote.d.ts +15 -1
  83. package/dist/lib/gh-remote.d.ts.map +1 -1
  84. package/dist/lib/gh-remote.js +27 -2
  85. package/dist/lib/gh-remote.js.map +1 -1
  86. package/dist/lib/gh-token-run.d.ts +140 -14
  87. package/dist/lib/gh-token-run.d.ts.map +1 -1
  88. package/dist/lib/gh-token-run.js +187 -15
  89. package/dist/lib/gh-token-run.js.map +1 -1
  90. package/dist/lib/git-identity.d.ts +6 -2
  91. package/dist/lib/git-identity.d.ts.map +1 -1
  92. package/dist/lib/git-identity.js +17 -8
  93. package/dist/lib/git-identity.js.map +1 -1
  94. package/dist/lib/guarded-read.d.ts +15 -0
  95. package/dist/lib/guarded-read.d.ts.map +1 -0
  96. package/dist/lib/guarded-read.js +73 -0
  97. package/dist/lib/guarded-read.js.map +1 -0
  98. package/dist/lib/machine-setup.d.ts +165 -0
  99. package/dist/lib/machine-setup.d.ts.map +1 -0
  100. package/dist/lib/machine-setup.js +441 -0
  101. package/dist/lib/machine-setup.js.map +1 -0
  102. package/dist/lib/native-realpath.d.ts +70 -0
  103. package/dist/lib/native-realpath.d.ts.map +1 -0
  104. package/dist/lib/native-realpath.js +95 -0
  105. package/dist/lib/native-realpath.js.map +1 -0
  106. package/dist/lib/project-config.d.ts +2 -6
  107. package/dist/lib/project-config.d.ts.map +1 -1
  108. package/dist/lib/project-config.js.map +1 -1
  109. package/dist/lib/project-name.d.ts +15 -0
  110. package/dist/lib/project-name.d.ts.map +1 -0
  111. package/dist/lib/project-name.js +22 -0
  112. package/dist/lib/project-name.js.map +1 -0
  113. package/dist/lib/push-to.d.ts +113 -0
  114. package/dist/lib/push-to.d.ts.map +1 -0
  115. package/dist/lib/push-to.js +240 -0
  116. package/dist/lib/push-to.js.map +1 -0
  117. package/dist/lib/runtime/claude-gateway-routing.d.ts +161 -0
  118. package/dist/lib/runtime/claude-gateway-routing.d.ts.map +1 -0
  119. package/dist/lib/runtime/claude-gateway-routing.js +466 -0
  120. package/dist/lib/runtime/claude-gateway-routing.js.map +1 -0
  121. package/dist/lib/runtime/codex-adapter.d.ts +91 -5
  122. package/dist/lib/runtime/codex-adapter.d.ts.map +1 -1
  123. package/dist/lib/runtime/codex-adapter.js +204 -44
  124. package/dist/lib/runtime/codex-adapter.js.map +1 -1
  125. package/dist/lib/runtime/codex-config.d.ts +6 -12
  126. package/dist/lib/runtime/codex-config.d.ts.map +1 -1
  127. package/dist/lib/runtime/codex-config.js +17 -24
  128. package/dist/lib/runtime/codex-config.js.map +1 -1
  129. package/dist/lib/runtime/codex-guard-proof.d.ts +4 -7
  130. package/dist/lib/runtime/codex-guard-proof.d.ts.map +1 -1
  131. package/dist/lib/runtime/codex-guard-proof.js +16 -14
  132. package/dist/lib/runtime/codex-guard-proof.js.map +1 -1
  133. package/dist/lib/runtime/codex-hooks-list.d.ts +20 -0
  134. package/dist/lib/runtime/codex-hooks-list.d.ts.map +1 -1
  135. package/dist/lib/runtime/codex-hooks-list.js +20 -8
  136. package/dist/lib/runtime/codex-hooks-list.js.map +1 -1
  137. package/dist/lib/runtime/types.d.ts +1 -1
  138. package/dist/lib/runtime/types.d.ts.map +1 -1
  139. package/dist/lib/standards.d.ts +3 -0
  140. package/dist/lib/standards.d.ts.map +1 -1
  141. package/dist/lib/standards.js +1 -0
  142. package/dist/lib/standards.js.map +1 -1
  143. package/dist/lib/team-identity.d.ts.map +1 -1
  144. package/dist/lib/team-identity.js +18 -53
  145. package/dist/lib/team-identity.js.map +1 -1
  146. package/dist/lib/team-restore.d.ts +281 -0
  147. package/dist/lib/team-restore.d.ts.map +1 -0
  148. package/dist/lib/team-restore.js +533 -0
  149. package/dist/lib/team-restore.js.map +1 -0
  150. package/dist/lib/window-view.d.ts +5 -0
  151. package/dist/lib/window-view.d.ts.map +1 -1
  152. package/dist/lib/window-view.js +67 -6
  153. package/dist/lib/window-view.js.map +1 -1
  154. package/dist/lib/worktree-sync.d.ts +139 -11
  155. package/dist/lib/worktree-sync.d.ts.map +1 -1
  156. package/dist/lib/worktree-sync.js +327 -46
  157. package/dist/lib/worktree-sync.js.map +1 -1
  158. package/dist/standards/merge-gates.md +26 -0
  159. package/package.json +2 -2
@@ -25,24 +25,134 @@
25
25
  * the devcontainer, then runs `mx-agent start team-builder` to define
26
26
  * their first agent team.
27
27
  */
28
- import { existsSync, mkdirSync, writeFileSync, chmodSync, readdirSync, realpathSync } from 'fs';
28
+ import { existsSync, mkdirSync, writeFileSync, chmodSync, readdirSync } from 'fs';
29
29
  import { dirname, join, resolve } from 'path';
30
30
  import { spawnSync } from 'child_process';
31
31
  import { fileURLToPath } from 'url';
32
32
  const __dirname = dirname(fileURLToPath(import.meta.url));
33
33
  import chalk from 'chalk';
34
34
  import { runInit } from './init.js';
35
- import { runCreate, isCatalogPreconditionRefusal, SELF_SERVICE_REFUSED_DETAIL } from './create.js';
35
+ import { runCreate, isCatalogPreconditionRefusal, SELF_SERVICE_REFUSED_DETAIL, redactErrorText } from './create.js';
36
36
  import { shellSingleQuote } from '../lib/memory.js';
37
37
  import { PROJECT_CONFIG_DEFAULTS, validateCoordinationServiceUrl, validateProjectConfig, } from '../lib/project-config.js';
38
- import { maybeCreateRemote } from '../lib/gh-remote.js';
38
+ import { maybeCreateRemote, PUSH_TIMEOUT_MS } from '../lib/gh-remote.js';
39
+ import { pushToRemote, validatePushToUrl } from '../lib/push-to.js';
40
+ import { redactUrlCredentials, stripAnsi } from '../lib/startup-report.js';
39
41
  import { requireCreationLogin } from '../lib/creation-login.js';
40
42
  import { CREDENTIAL_LIMIT_REACHED_DETAIL, CREDENTIAL_NO_USER_KEY_DETAIL, CREDENTIAL_NOT_AUTHORIZED_DETAIL, } from '../lib/coordination-token.js';
41
43
  import { findTeamWorktree } from '../lib/worktree.js';
42
44
  import { TEAM_BUILDER_ROLEGUIDE, newProjectDockerfileTemplate, newProjectDevcontainerJsonTemplate, newProjectPostCreateShTemplate, newProjectPostStartShTemplate, newProjectGitignoreTemplate, newProjectMxAgentCliVersionPinTemplate, } from '../lib/templates.js';
43
45
  import { runningCliVersion } from '../lib/framework-version.js';
44
46
  import { checkWorktreeConfigPreflight, describePreflight } from '../lib/git-identity.js';
47
+ import { setWorktreeConfigExtension } from '../lib/machine-setup.js';
45
48
  import { scrubGitRedirectEnv } from '../lib/git-scrub-env.js';
49
+ import { validateProjectName } from '../lib/project-name.js';
50
+ import { nativeRealpath, normaliseResolvedPath, pathFor, sameResolvedPath } from '../lib/native-realpath.js';
51
+ // Re-exported so imports of `validateProjectName` from this file keep working.
52
+ // The rule lives in a pure module the surface web app bundles (#1111 item 5).
53
+ export { validateProjectName };
54
+ // ── The `--json` contract (#1111 item 3, amendment 1 SF7) ─────────────
55
+ /** Every `steps[].name` the document can hold. Pinned in a test and the PR body. */
56
+ export const NEW_PROJECT_STEP_NAMES = [
57
+ 'validate', 'login-check', 'git-init', 'scaffold', 'initial-commit', 'config-sync',
58
+ 'provision', 'catalog-commit', 'create-remote', 'push',
59
+ ];
60
+ /** Every `error.code` the document can hold. Pinned in a test and the PR body. */
61
+ export const NEW_PROJECT_ERROR_CODES = [
62
+ 'invalid-name', 'invalid-push-url', 'flag-conflict', 'invalid-config', 'dir-not-empty',
63
+ 'login-missing', 'git-init-failed', 'git-dir-redirected', 'commit-failed', 'provision-failed',
64
+ 'gh-missing', 'gh-version-failed', 'gh-unauthenticated', 'gh-timed-out', 'gh-failed',
65
+ 'push-failed', 'push-timeout', 'remote-not-empty', 'remote-missing', 'remote-unreachable', 'usage', 'internal',
66
+ ];
67
+ /** The `result` of each `--push-to` failure (#1111 amendments 1 and 2). */
68
+ export const PUSH_TO_REASON_OUTCOME = {
69
+ 'push-failed': 'fail',
70
+ 'push-timeout': 'could-not-run',
71
+ 'remote-not-empty': 'fail',
72
+ 'remote-missing': 'fail',
73
+ 'remote-unreachable': 'could-not-run',
74
+ };
75
+ /**
76
+ * The result and exit code of each `--with-remote` failure reason (#1111
77
+ * amendment 1, MF4). A remote that was never reached is could-not-run (2); a
78
+ * `gh repo create` or push that ran and failed is fail (1). Exit 0 before #1111.
79
+ */
80
+ export const REMOTE_REASON_OUTCOME = {
81
+ 'gh-missing': 'could-not-run',
82
+ 'gh-version-failed': 'could-not-run',
83
+ 'gh-unauthenticated': 'could-not-run',
84
+ 'gh-timed-out': 'could-not-run',
85
+ 'gh-failed': 'fail',
86
+ 'push-failed': 'fail',
87
+ 'push-timeout': 'could-not-run',
88
+ };
89
+ /** 0 pass, 1 fail, 2 could-not-run, as `provision --recheck --json`. */
90
+ export function exitCodeForResult(result) {
91
+ return result === 'pass' ? 0 : result === 'fail' ? 1 : 2;
92
+ }
93
+ /** A refusal or abort with its `error.code`. Its message is what the non-JSON run printed. */
94
+ export class NewProjectRefusal extends Error {
95
+ code;
96
+ step;
97
+ constructor(code, step, message) {
98
+ super(message);
99
+ this.code = code;
100
+ this.step = step;
101
+ this.name = 'NewProjectRefusal';
102
+ }
103
+ }
104
+ /**
105
+ * The document, as a value. `result` is `fail` when a required step failed,
106
+ * otherwise `could-not-run` when a required step could not run, otherwise
107
+ * `pass`. `error` names the first required step whose result is the document's.
108
+ * Every detail and the message are redacted with `redactErrorText(stripAnsi())`,
109
+ * as `provision --recheck --json` does (security review of #1093).
110
+ */
111
+ export function newProjectDocument(i) {
112
+ const required = i.steps.filter((s) => s.required);
113
+ const result = required.some((s) => s.result === 'fail')
114
+ ? 'fail'
115
+ : required.some((s) => s.result === 'could-not-run') ? 'could-not-run' : 'pass';
116
+ const clean = (t) => redactErrorText(stripAnsi(t));
117
+ const first = result === 'pass' ? undefined : required.find((s) => s.result === result);
118
+ return {
119
+ schema_version: 1,
120
+ project: i.project,
121
+ result,
122
+ environment: { platform: i.platform ?? process.platform },
123
+ error: first ? { code: first.code ?? 'internal', message: clean(first.detail) } : null,
124
+ steps: i.steps.map((s) => ({ name: s.name, result: s.result, required: s.required, detail: clean(s.detail) })),
125
+ files: i.files ?? [],
126
+ url: i.url ? redactUrlCredentials(stripAnsi(i.url)) : null,
127
+ };
128
+ }
129
+ /**
130
+ * The document for a command line the parser refused before `runNew` ran, such
131
+ * as an unknown option (QA on PR #1120: `new project -lead --json` exited 1
132
+ * with no document). Exit 2, `usage`. The caller in `index.ts` writes it only
133
+ * when `--json` is on the command line.
134
+ */
135
+ export function newProjectUsageDocument(message) {
136
+ return newProjectDocument({
137
+ project: '',
138
+ steps: [{ name: 'validate', result: 'could-not-run', required: true, detail: message || 'the command line was refused', code: 'usage' }],
139
+ });
140
+ }
141
+ /** A copy of `env` without GH_TOKEN, for children that do not push. */
142
+ function withoutGhToken(env) {
143
+ const copy = { ...env };
144
+ delete copy.GH_TOKEN;
145
+ return copy;
146
+ }
147
+ /** `git ls-files` in the new repository, or [] when it cannot be read. */
148
+ function trackedFiles(outputDir) {
149
+ if (!outputDir || !existsSync(join(outputDir, '.git')))
150
+ return [];
151
+ const r = spawnSync('git', ['-C', outputDir, 'ls-files', '-z'], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
152
+ if (r.error || r.status !== 0)
153
+ return [];
154
+ return String(r.stdout ?? '').split('\0').filter((f) => f !== '');
155
+ }
46
156
  /**
47
157
  * The named step for the three credential failures an operator meets first on
48
158
  * a new project (#607, #610), or null for every other failure.
@@ -176,15 +286,6 @@ export function nextStepLines(projectName, firstTeam) {
176
286
  ` 3. ${chalk.cyan('mx-agent start <team>')} ${chalk.dim('# Start an isolated Claude session')}`,
177
287
  ];
178
288
  }
179
- /** Validate project name: letters, digits, hyphens/underscores, 1-50 chars, must start with letter or digit */
180
- function validateProjectName(name) {
181
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,49}$/.test(name)) {
182
- throw new Error(`Invalid project name "${name}". Use letters, digits, hyphens, or underscores (1–50 chars, must start with a letter or digit).`);
183
- }
184
- if (/[;|&$`()><]/.test(name) || name.includes('..') || name.includes('/') || name.includes('\\')) {
185
- throw new Error(`Project name "${name}" contains disallowed characters.`);
186
- }
187
- }
188
289
  function logCreated(path) {
189
290
  console.log(chalk.green(' ✓ created ') + chalk.dim(path));
190
291
  }
@@ -210,7 +311,7 @@ export function pushFailedNote(outputDir, repoUrl) {
210
311
  ' provision refuses while origin has no branches.',
211
312
  ];
212
313
  }
213
- const runGitConfig = (args) => spawnSync('git', args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
314
+ const runGitConfigDefault = (args) => spawnSync('git', args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
214
315
  /**
215
316
  * Turn on `extensions.worktreeConfig` in the repository `new project` just
216
317
  * created (#448, plan #857).
@@ -221,39 +322,55 @@ const runGitConfig = (args) => spawnSync('git', args, { encoding: 'utf-8', stdio
221
322
  * completion row 15 as could-not-run and its teams committed under the shared
222
323
  * identity. It runs right after `git init`, before any worktree exists, so the
223
324
  * change reaches no other team: this repository has no other worktree yet.
224
- * `lib/git-identity.ts` still never enables the extension on a shared repository.
225
325
  *
226
- * Guarded by the same pre-flight the shared case uses (`core.bare`,
227
- * `core.worktree`, `core.sparseCheckout`, git-worktree(1) CONFIGURATION FILE).
228
- * A fresh `git init` sets none of them, but a global template or init config
229
- * could, and then enabling the extension needs a manual migration first.
326
+ * ONE WRITER (#1155 slice 2). The decision and the write are
327
+ * `setWorktreeConfigExtension` in `lib/machine-setup.ts`, the function
328
+ * `mx-agent start` also calls. Its rule is the one this step always relied on:
329
+ * write only when the repository has no linked worktree other than the main one
330
+ * and the pre-flight passes (`core.bare`, `core.worktree`,
331
+ * `core.sparseCheckout`, git-worktree(1) CONFIGURATION FILE). A fresh `git init`
332
+ * sets none of them, but a global template or init config could, and then
333
+ * enabling the extension needs a manual migration first.
230
334
  *
231
335
  * FAIL-OPEN, the tier the identity write in `create.ts` uses: a missing extension
232
336
  * degrades attribution and does not endanger the project, so a refusal or a
233
337
  * failed `git config` prints a warning naming the remedy and creation continues.
234
- * It never calls process.exit. It writes with `--local` so the value goes into
338
+ * It never calls process.exit. The write uses `--local` so the value goes into
235
339
  * this repository's own `.git/config`, the only place git reads extensions from.
340
+ *
341
+ * The three return values are pinned by `new-project-worktree-config.test.ts`:
342
+ * `enabled` (set now, or already on), `refused` (the pre-flight, another
343
+ * worktree, or an unreadable repository), `failed` (the git write failed).
236
344
  */
237
- export function enableWorktreeConfig(repoPath, run = runGitConfig) {
345
+ export function enableWorktreeConfig(repoPath, run = runGitConfigDefault) {
238
346
  const remedy = `git -C ${shellSingleQuote(repoPath)} config extensions.worktreeConfig true`;
239
347
  const consequence = 'Until it is on, team worktrees commit under the repository\'s shared git identity and completion row 15 reports could-not-run.';
240
- const preflight = checkWorktreeConfigPreflight(repoPath);
241
- if (preflight.couldNotRun !== null || !preflight.safe) {
242
- console.log(chalk.yellow(` ! extensions.worktreeConfig NOT enabled: pre-flight ${describePreflight(preflight)}.`));
243
- console.log(chalk.yellow(` ${consequence}`));
244
- console.log(chalk.yellow(` Move the blocking setting to the main worktree's config.worktree (git-worktree(1)), then run: ${remedy}`));
245
- return 'refused';
348
+ const result = setWorktreeConfigExtension({ projectRoot: repoPath, mode: 'apply', runGitConfig: run });
349
+ if (result.status === 'set' || result.status === 'already-set') {
350
+ console.log(chalk.green(' ✓ extensions.worktreeConfig enabled'));
351
+ return 'enabled';
246
352
  }
247
- const r = run(['-C', repoPath, 'config', '--local', 'extensions.worktreeConfig', 'true']);
248
- if (r.error || r.status !== 0) {
249
- const why = (r.error ? r.error.message : String(r.stderr ?? '')).replace(/\s+/g, ' ').trim().slice(0, 240);
250
- console.log(chalk.yellow(` ! extensions.worktreeConfig NOT enabled: git config exited ${r.status ?? 'without a status'}${why ? `: ${why}` : ''}.`));
353
+ if (result.cause === 'write-failed') {
354
+ const status = result.writeError?.status ?? null;
355
+ const why = result.writeError?.why ?? '';
356
+ console.log(chalk.yellow(` ! extensions.worktreeConfig NOT enabled: git config exited ${status ?? 'without a status'}${why ? `: ${why}` : ''}.`));
251
357
  console.log(chalk.yellow(` ${consequence}`));
252
358
  console.log(chalk.yellow(` To enable it, run: ${remedy}`));
253
359
  return 'failed';
254
360
  }
255
- console.log(chalk.green(' ✓ extensions.worktreeConfig enabled'));
256
- return 'enabled';
361
+ // The pre-flight refused, the repository could not be read, or it already has
362
+ // another worktree. Each prints the pre-flight reading, as this step always has.
363
+ if (result.cause === 'other-worktrees' || result.cause === 'present-value') {
364
+ console.log(chalk.yellow(` ! extensions.worktreeConfig NOT enabled: ${result.detail}.`));
365
+ console.log(chalk.yellow(` ${consequence}`));
366
+ console.log(chalk.yellow(` To enable it, run: ${remedy}`));
367
+ return 'refused';
368
+ }
369
+ const preflight = checkWorktreeConfigPreflight(repoPath);
370
+ console.log(chalk.yellow(` ! extensions.worktreeConfig NOT enabled: pre-flight ${describePreflight(preflight)}.`));
371
+ console.log(chalk.yellow(` ${consequence}`));
372
+ console.log(chalk.yellow(` Move the blocking setting to the main worktree's config.worktree (git-worktree(1)), then run: ${remedy}`));
373
+ return 'refused';
257
374
  }
258
375
  /**
259
376
  * Delete from `env`, in place, every key `scrubGitRedirectEnv` drops (plan #864
@@ -274,13 +391,20 @@ export function removeGitRedirectVars(env) {
274
391
  * named list does not cover. `git init` has already run by then, so the text
275
392
  * says git may already have acted on the directory it names.
276
393
  *
277
- * Both sides go through realpath, so an `outputDir` reached through a
278
- * symlinked parent is not refused.
394
+ * Both sides go through `nativeRealpath` (`lib/native-realpath.ts`, for #1123),
395
+ * so an `outputDir` reached through a symlinked parent is not refused, and on
396
+ * win32 an 8.3 short name, a forward slash against a backslash, a `\\?\` prefix
397
+ * and drive-letter case are not refused either. Any other difference in letter
398
+ * case refuses: there is no case fold. Fail-closed both ways: an `outputDir`
399
+ * that cannot be resolved refuses, and a git path that cannot be resolved is
400
+ * compared as printed (spelling normalised on win32), which refuses on any
401
+ * other difference. `realpath` is for tests only.
279
402
  */
280
- export function ownGitDirProblem(outputDir, env) {
403
+ export function ownGitDirProblem(outputDir, env, realpath = {}) {
404
+ const platform = realpath.platform ?? process.platform;
281
405
  let expected;
282
406
  try {
283
- expected = join(realpathSync(outputDir), '.git');
407
+ expected = normaliseResolvedPath(pathFor(platform).join(nativeRealpath(outputDir, realpath), '.git'), platform);
284
408
  }
285
409
  catch (err) {
286
410
  return `could not resolve ${outputDir}: ${err instanceof Error ? err.message : String(err)}`;
@@ -293,12 +417,12 @@ export function ownGitDirProblem(outputDir, env) {
293
417
  return `git rev-parse --absolute-git-dir in ${outputDir} exited ${r.status ?? 'without a status'}${why ? `: ${why}` : ''}. Expected ${expected}.`;
294
418
  }
295
419
  const resolvedRaw = String(r.stdout ?? '').trim();
296
- let resolvedReal = resolvedRaw;
420
+ let resolvedReal = normaliseResolvedPath(resolvedRaw, platform);
297
421
  try {
298
- resolvedReal = realpathSync(resolvedRaw);
422
+ resolvedReal = nativeRealpath(resolvedRaw, realpath);
299
423
  }
300
424
  catch { /* compared as printed */ }
301
- if (resolvedReal === expected)
425
+ if (sameResolvedPath(resolvedReal, expected, platform))
302
426
  return null;
303
427
  return `git resolved the git directory for ${outputDir} to ${resolvedRaw}, not ${expected}. `
304
428
  + `git may already have acted on ${resolvedRaw}: git init ran with this environment before this check.`;
@@ -307,8 +431,8 @@ export function ownGitDirProblem(outputDir, env) {
307
431
  * Exit non-zero, before any further write, when `ownGitDirProblem` reports one.
308
432
  * Fail-closed: writing on would commit into another repository.
309
433
  */
310
- export function refuseUnlessOwnGitDir(outputDir, env) {
311
- const problem = ownGitDirProblem(outputDir, env);
434
+ export function refuseUnlessOwnGitDir(outputDir, env, realpath = {}) {
435
+ const problem = ownGitDirProblem(outputDir, env, realpath);
312
436
  if (problem === null)
313
437
  return;
314
438
  console.error(chalk.red(`Error: refusing to continue. ${problem}`));
@@ -316,7 +440,85 @@ export function refuseUnlessOwnGitDir(outputDir, env) {
316
440
  console.error(chalk.dim(` Nothing else was written to ${outputDir}.`));
317
441
  process.exit(1);
318
442
  }
319
- export async function runNew(projectName, options) {
443
+ /**
444
+ * `mx-agent new project <name>`. Without `--json` every line and exit is what
445
+ * it was before #1111, except that a failed `--with-remote` remote step now
446
+ * exits 1 or 2 (amendment 1, MF4) instead of 0.
447
+ */
448
+ export async function runNew(projectName, options, deps = {}) {
449
+ if (options.json)
450
+ return runNewJson(projectName, options, deps);
451
+ const run = { json: false, steps: [], current: 'validate' };
452
+ await newProjectBody(projectName, options, deps, run);
453
+ }
454
+ /**
455
+ * `new project --json` (#1111 item 3, amendment 1 MF1). The shape of
456
+ * `runRecheckJson` in create.ts:
457
+ * - STDOUT HOLDS ONE DOCUMENT, written by one `process.stdout.write` at the
458
+ * end. For the whole run `console.log` and `console.info` print through
459
+ * `console.error`, and `gh repo create`'s stdout is fd 2;
460
+ * - EVERY EXIT THAT RETURNS HERE WRITES A DOCUMENT. A refusal or a throw adds a
461
+ * `could-not-run` step naming why. A `process.exit` inside provisioning is
462
+ * not caught: it exits 1 with no document, which a consumer reads as
463
+ * could-not-run, the rule `provision --recheck --json` states;
464
+ * - exit 0 pass, 1 fail, 2 could-not-run, through `process.exitCode`.
465
+ */
466
+ async function runNewJson(projectName, options, deps) {
467
+ const run = { json: true, steps: [], current: 'validate' };
468
+ const savedLog = console.log;
469
+ const savedInfo = console.info;
470
+ // Looked up at call time, so a test's spy on `console.error` sees these lines.
471
+ console.log = (...a) => console.error(...a);
472
+ console.info = (...a) => console.error(...a);
473
+ let failure = null;
474
+ try {
475
+ await newProjectBody(projectName, options, deps, run);
476
+ }
477
+ catch (err) {
478
+ failure = err;
479
+ }
480
+ finally {
481
+ console.log = savedLog;
482
+ console.info = savedInfo;
483
+ }
484
+ if (failure !== null) {
485
+ const message = failure instanceof Error ? failure.message : String(failure);
486
+ run.steps.push({
487
+ name: failure instanceof NewProjectRefusal ? failure.step : run.current,
488
+ result: 'could-not-run',
489
+ required: true,
490
+ detail: message || 'the step threw with no message',
491
+ code: failure instanceof NewProjectRefusal ? failure.code : 'internal',
492
+ });
493
+ // Redacted on stderr too: a consumer may log both streams.
494
+ console.error(redactErrorText(stripAnsi(message)));
495
+ }
496
+ const doc = newProjectDocument({ project: projectName, steps: run.steps, files: trackedFiles(run.outputDir), url: run.url ?? null });
497
+ process.stdout.write(JSON.stringify(doc, null, 2) + '\n');
498
+ process.exitCode = exitCodeForResult(doc.result);
499
+ }
500
+ async function newProjectBody(projectName, options, deps, run) {
501
+ const step = (name, result, detail, extra = {}) => {
502
+ run.steps.push({ name, result, required: extra.required ?? true, detail, ...(extra.code ? { code: extra.code } : {}) });
503
+ };
504
+ // A refusal: without --json, the lines and the exit this function printed
505
+ // before #1111; with --json, a throw the wrapper turns into a document.
506
+ const refuse = (code, lines) => {
507
+ if (run.json)
508
+ throw new NewProjectRefusal(code, run.current, lines.join('\n'));
509
+ for (const line of lines)
510
+ console.error(line);
511
+ process.exit(1);
512
+ };
513
+ // A throw from a check: the same message, carrying its code.
514
+ const asRefusal = (code, fn) => {
515
+ try {
516
+ fn();
517
+ }
518
+ catch (err) {
519
+ throw new NewProjectRefusal(code, run.current, err instanceof Error ? err.message : String(err));
520
+ }
521
+ };
320
522
  // Before any git call: remove git's repository-redirect variables from this
321
523
  // process's own environment (for #860, plan #864 revision 3). An inherited
322
524
  // GIT_DIR or GIT_WORK_TREE would point every git call at another repository,
@@ -325,22 +527,44 @@ export async function runNew(projectName, options) {
325
527
  // calls and every spawn below without editing lib/. scrubGitRedirectEnv
326
528
  // holds the one list; this deletes exactly the keys it drops.
327
529
  removeGitRedirectVars(process.env);
328
- validateProjectName(projectName);
530
+ // The #1111 flags, checked before anything else so a refusal writes nothing.
531
+ // A run without them meets none of these checks.
532
+ const usesNewFlags = options.scaffoldOnly === true || options.pushTo !== undefined || options.json === true;
533
+ if (usesNewFlags && !projectName) {
534
+ throw new NewProjectRefusal('invalid-name', 'validate', 'Error: --scaffold-only, --push-to and --json need a project name: mx-agent new project <name> ...');
535
+ }
536
+ if (options.pushTo !== undefined && !options.scaffoldOnly) {
537
+ throw new NewProjectRefusal('flag-conflict', 'validate', 'Error: --push-to needs --scaffold-only.');
538
+ }
539
+ if (options.scaffoldOnly && options.withRemote) {
540
+ throw new NewProjectRefusal('flag-conflict', 'validate', 'Error: --with-remote cannot be used with --scaffold-only. --with-remote creates the repository with gh; use --push-to <url> for a repository that exists.');
541
+ }
542
+ asRefusal('invalid-name', () => validateProjectName(projectName));
543
+ const pushTo = options.pushTo === undefined
544
+ ? undefined
545
+ : (() => {
546
+ let checked = '';
547
+ asRefusal('invalid-push-url', () => { checked = (deps.validatePushUrl ?? validatePushToUrl)(options.pushTo); });
548
+ return checked;
549
+ })();
329
550
  // Every value that will end up in the new project's mx-agent.config.json is
330
551
  // checked BEFORE the directory exists, by the same function that checks the file
331
552
  // on the next read. A refusal after mkdirSync leaves a half-scaffolded project
332
553
  // the operator cleans up by hand (#59 amendment 3, Should Fix). This is why
333
554
  // `--worktree-dir '../escape'` creates nothing: the traversal check runs here,
334
555
  // not after four directories and a git init.
335
- const coordinationServiceUrl = options.coordinationServiceUrl
336
- ? validateCoordinationServiceUrl(options.coordinationServiceUrl)
337
- : undefined;
338
- validateProjectConfig({
339
- baseBranch: options.baseBranch ?? PROJECT_CONFIG_DEFAULTS.baseBranch,
340
- worktreeDir: options.worktreeDir ?? PROJECT_CONFIG_DEFAULTS.worktreeDir,
341
- configSource: options.configSource ?? PROJECT_CONFIG_DEFAULTS.configSource,
342
- projectSlug: projectName,
343
- ...(coordinationServiceUrl ? { coordinationServiceUrl } : {}),
556
+ let coordinationServiceUrl;
557
+ asRefusal('invalid-config', () => {
558
+ coordinationServiceUrl = options.coordinationServiceUrl
559
+ ? validateCoordinationServiceUrl(options.coordinationServiceUrl)
560
+ : undefined;
561
+ validateProjectConfig({
562
+ baseBranch: options.baseBranch ?? PROJECT_CONFIG_DEFAULTS.baseBranch,
563
+ worktreeDir: options.worktreeDir ?? PROJECT_CONFIG_DEFAULTS.worktreeDir,
564
+ configSource: options.configSource ?? PROJECT_CONFIG_DEFAULTS.configSource,
565
+ projectSlug: projectName,
566
+ ...(coordinationServiceUrl ? { coordinationServiceUrl } : {}),
567
+ });
344
568
  });
345
569
  const outputDir = options.dir ? resolve(options.dir) : resolve(process.cwd(), projectName);
346
570
  if (existsSync(outputDir)) {
@@ -352,14 +576,22 @@ export async function runNew(projectName, options) {
352
576
  /* ignore */
353
577
  }
354
578
  if (entries.length > 0) {
355
- console.error(chalk.red(`Error: Directory already exists and is not empty: ${outputDir}`));
356
- console.error(chalk.dim('Use a different project name or remove the existing directory.'));
357
- process.exit(1);
579
+ refuse('dir-not-empty', [
580
+ chalk.red(`Error: Directory already exists and is not empty: ${outputDir}`),
581
+ chalk.dim('Use a different project name or remove the existing directory.'),
582
+ ]);
358
583
  }
359
584
  }
585
+ step('validate', 'pass', `name, flags${pushTo !== undefined ? ', push URL' : ''} and config values accepted; ${outputDir} is absent or empty`);
360
586
  // After the checks above, so a bad name is reported as a bad name, and before
361
587
  // `mkdirSync` below, so a missing login leaves nothing to clean up (#818).
362
- requireCreationLogin({ withRemote: options.withRemote === true });
588
+ // Not under --scaffold-only (#1111 item 1): that route provisions no team, so
589
+ // it needs no MemNexus key, and it never runs gh.
590
+ if (!options.scaffoldOnly) {
591
+ run.current = 'login-check';
592
+ asRefusal('login-missing', () => requireCreationLogin({ withRemote: options.withRemote === true }));
593
+ step('login-check', 'pass', options.withRemote ? 'a MemNexus user key resolves, and gh runs and is logged in' : 'a MemNexus user key resolves');
594
+ }
363
595
  console.log();
364
596
  console.log(chalk.cyan.bold('Creating new mx-agent project'));
365
597
  console.log(chalk.dim('─'.repeat(50)));
@@ -368,17 +600,27 @@ export async function runNew(projectName, options) {
368
600
  console.log();
369
601
  // 1. Create directory
370
602
  mkdirSync(outputDir, { recursive: true });
603
+ run.outputDir = outputDir;
371
604
  // 2. git init — force branch name to 'main'
605
+ run.current = 'git-init';
372
606
  console.log(chalk.dim(' Initialising git repository...'));
373
607
  const gitInit = spawnSync('git', ['init', outputDir], { encoding: 'utf-8', stdio: 'pipe' });
374
608
  if (gitInit.status !== 0) {
375
- console.error(chalk.red(`Error: git init failed: ${gitInit.stderr}`));
376
- process.exit(1);
609
+ refuse('git-init-failed', [chalk.red(`Error: git init failed: ${gitInit.stderr}`)]);
377
610
  }
378
611
  // 2-check. Fail-closed before any further write (plan #864 item 3).
379
- refuseUnlessOwnGitDir(outputDir, process.env);
612
+ if (run.json) {
613
+ const problem = ownGitDirProblem(outputDir, process.env);
614
+ if (problem !== null)
615
+ refuse('git-dir-redirected', [`Error: refusing to continue. ${problem}`]);
616
+ }
617
+ else {
618
+ refuseUnlessOwnGitDir(outputDir, process.env);
619
+ }
380
620
  spawnSync('git', ['-C', outputDir, 'symbolic-ref', 'HEAD', 'refs/heads/main'], { stdio: 'pipe' });
381
621
  console.log(chalk.green(' ✓ git init (branch: main)'));
622
+ step('git-init', 'pass', `git init ${outputDir}, branch main`);
623
+ run.current = 'scaffold';
382
624
  // 2a. extensions.worktreeConfig, before any worktree exists (#448, plan #857).
383
625
  // Fail-open: the result is printed, and creation continues either way.
384
626
  enableWorktreeConfig(outputDir);
@@ -430,6 +672,8 @@ export async function runNew(projectName, options) {
430
672
  const roleguidesDir = join(outputDir, PROJECT_CONFIG_DEFAULTS.roleguidesDir);
431
673
  mkdirSync(roleguidesDir, { recursive: true });
432
674
  writeFile(join(roleguidesDir, 'team-builder.md'), TEAM_BUILDER_ROLEGUIDE);
675
+ step('scaffold', 'pass', 'devcontainer, mx-agent.config.json, mx-agent-system and the team-builder roleguide written');
676
+ run.current = 'initial-commit';
433
677
  // 7. Initial git commit — HARD required. Without it, the main branch has no commits
434
678
  // and subsequent `mx-agent provision` calls fail with git "fatal: invalid reference"
435
679
  // errors. Better to fail loudly here with an actionable message than to leave the
@@ -455,19 +699,24 @@ export async function runNew(projectName, options) {
455
699
  }
456
700
  console.log(chalk.dim(' (set local git identity — run git config --global user.name/email to personalise)'));
457
701
  }
458
- spawnSync('git', ['add', '-A'], { cwd: outputDir, stdio: 'pipe' });
459
- const commit = spawnSync('git', ['commit', '-m', `feat: scaffold ${projectName} with mx-agent`], { cwd: outputDir, encoding: 'utf-8', stdio: 'pipe' });
702
+ // Under --push-to, GH_TOKEN reaches only the push (security review on PR
703
+ // #1120, INFO 1): the commits and config-sync below get an env without it.
704
+ // Without --push-to, `noToken` is undefined and every child inherits as before.
705
+ const noToken = pushTo !== undefined ? withoutGhToken(process.env) : undefined;
706
+ spawnSync('git', ['add', '-A'], { cwd: outputDir, stdio: 'pipe', ...(noToken ? { env: noToken } : {}) });
707
+ const commit = spawnSync('git', ['commit', '-m', `feat: scaffold ${projectName} with mx-agent`], { cwd: outputDir, encoding: 'utf-8', stdio: 'pipe', ...(noToken ? { env: noToken } : {}) });
460
708
  if (commit.status !== 0) {
461
- console.error();
462
- console.error(chalk.red('Error: failed to create initial commit.'));
463
- if (commit.stderr) {
464
- console.error(chalk.dim(` git stderr: ${commit.stderr.trim()}`));
465
- }
466
- console.error();
467
- console.error(chalk.dim(` After fixing, remove ${outputDir} and re-run 'mx-agent new ${projectName}'.`));
468
- process.exit(1);
709
+ refuse('commit-failed', [
710
+ '',
711
+ chalk.red('Error: failed to create initial commit.'),
712
+ ...(commit.stderr ? [chalk.dim(` git stderr: ${commit.stderr.trim()}`)] : []),
713
+ '',
714
+ chalk.dim(` After fixing, remove ${outputDir} and re-run 'mx-agent new ${projectName}'.`),
715
+ ]);
469
716
  }
470
717
  console.log(chalk.green(' ✓ initial commit'));
718
+ step('initial-commit', 'pass', `feat: scaffold ${projectName} with mx-agent`);
719
+ run.current = 'config-sync';
471
720
  // 7a. Run config-sync to upgrade from the minimal init stubs to the full
472
721
  // bundled agent-config surface (hooks, agents, skills, templates). Uses a
473
722
  // subprocess to avoid process.exit calls in runConfigSync.
@@ -475,25 +724,34 @@ export async function runNew(projectName, options) {
475
724
  console.log(chalk.dim(' Syncing full agent configuration...'));
476
725
  const configSyncResult = spawnSync(process.execPath, [
477
726
  ...process.execArgv,
478
- join(__dirname, '..', 'index.js'),
727
+ deps.cliEntry ?? join(__dirname, '..', 'index.js'),
479
728
  'config-sync', '--apply', '--force', '--allow-dirty',
480
- ], { cwd: outputDir, stdio: 'pipe', encoding: 'utf-8', env: { ...process.env } });
729
+ ], { cwd: outputDir, stdio: 'pipe', encoding: 'utf-8', env: noToken ?? { ...process.env } });
481
730
  if (configSyncResult.status === 0) {
482
731
  console.log(chalk.green(' ✓ full agent configuration synced'));
483
732
  // Commit the upgraded config files
733
+ let committed = false;
484
734
  try {
485
- spawnSync('git', ['add', '-A'], { cwd: outputDir, stdio: 'pipe' });
486
- spawnSync('git', ['commit', '-m', 'chore: sync full agent configuration via config-sync'], { cwd: outputDir, stdio: 'pipe' });
735
+ spawnSync('git', ['add', '-A'], { cwd: outputDir, stdio: 'pipe', ...(noToken ? { env: noToken } : {}) });
736
+ committed = spawnSync('git', ['commit', '-m', 'chore: sync full agent configuration via config-sync'], { cwd: outputDir, stdio: 'pipe', ...(noToken ? { env: noToken } : {}) }).status === 0;
487
737
  }
488
738
  catch {
489
739
  // If nothing changed or commit fails, that's fine
490
740
  }
741
+ step('config-sync', 'pass', committed ? 'chore: sync full agent configuration via config-sync' : 'config-sync ran; nothing new to commit', { required: false });
491
742
  }
492
743
  else {
493
744
  console.log(chalk.yellow(' ⚠ config-sync failed — run "mx-agent config-sync --apply" manually'));
494
745
  if (configSyncResult.stderr) {
495
746
  console.log(chalk.dim(` ${configSyncResult.stderr.trim().split('\n')[0]}`));
496
747
  }
748
+ // Fail-open, as before #1111: the step is recorded and does not fail the run.
749
+ step('config-sync', 'fail', `config-sync exited ${configSyncResult.status ?? 'without a status'}: ${(configSyncResult.stderr ?? '').trim().split('\n')[0] ?? ''}`, { required: false });
750
+ }
751
+ // --scaffold-only stops here (#1111 item 1): no team, no catalog commit, no gh.
752
+ if (options.scaffoldOnly) {
753
+ finishScaffoldOnly(projectName, outputDir, pushTo, deps, run, configSyncResult.status === 0);
754
+ return;
497
755
  }
498
756
  // 7b. Provision team-builder worktree (initial commit is now guaranteed above).
499
757
  //
@@ -508,6 +766,7 @@ export async function runNew(projectName, options) {
508
766
  console.log(chalk.dim(' Provisioning team-builder...'));
509
767
  const teamBuilderRoleguide = join(PROJECT_CONFIG_DEFAULTS.roleguidesDir, 'team-builder.md');
510
768
  let provisionFailure = null;
769
+ run.current = 'provision';
511
770
  try {
512
771
  await runCreate({
513
772
  roleguide: teamBuilderRoleguide,
@@ -518,9 +777,11 @@ export async function runNew(projectName, options) {
518
777
  newProjectTeamBuilder: true,
519
778
  });
520
779
  console.log(chalk.green(' ✓ team-builder provisioned'));
780
+ step('provision', 'pass', 'team-builder provisioned');
521
781
  }
522
782
  catch (err) {
523
783
  provisionFailure = provisionFailureMessage(err);
784
+ step('provision', 'fail', provisionFailure, { code: 'provision-failed' });
524
785
  console.log(chalk.yellow(` ⚠ Could not provision team-builder: ${provisionFailure}`));
525
786
  // The SAME command, which is now a resume rather than a refusal (#5, #316).
526
787
  // It used to print an instruction that met `Worktree already exists` and
@@ -555,7 +816,11 @@ export async function runNew(projectName, options) {
555
816
  if (!tracked && existsSync(join(outputDir, catalogEntryRel))) {
556
817
  const staged = spawnSync('git', ['add', '--', catalogEntryRel], { cwd: outputDir, stdio: 'pipe' });
557
818
  if (staged.status === 0) {
558
- spawnSync('git', ['commit', '-m', 'chore: add the team-builder catalog entry'], { cwd: outputDir, stdio: 'pipe' });
819
+ const made = spawnSync('git', ['commit', '-m', 'chore: add the team-builder catalog entry'], { cwd: outputDir, stdio: 'pipe' });
820
+ // Fail-open, as before #1111.
821
+ step('catalog-commit', made.status === 0 ? 'pass' : 'fail', made.status === 0
822
+ ? 'chore: add the team-builder catalog entry'
823
+ : `git commit exited ${made.status ?? 'without a status'}`, { required: false });
559
824
  }
560
825
  }
561
826
  }
@@ -567,11 +832,22 @@ export async function runNew(projectName, options) {
567
832
  // team-builder catalog entry and the next `provision` in this project finds
568
833
  // it on the remote's base branch.
569
834
  let remoteUrl = null;
835
+ run.current = 'create-remote';
570
836
  const remoteResult = await maybeCreateRemote(outputDir, projectName, {
571
837
  withRemote: options.withRemote,
572
838
  remoteVisibility: options.remoteVisibility,
839
+ ...(run.json ? { stdoutToStderr: true } : {}),
573
840
  });
574
841
  if (options.withRemote) {
842
+ // Exit 1 or 2 by reason, not 0 (#1111 item 3, amendment 1 MF4).
843
+ if (remoteResult.created) {
844
+ step('create-remote', 'pass', `gh repo create --push: ${remoteResult.repoUrl ?? 'created'}`);
845
+ if (remoteResult.repoUrl)
846
+ run.url = remoteResult.repoUrl;
847
+ }
848
+ else if (remoteResult.reason && remoteResult.reason !== 'not-requested') {
849
+ step('create-remote', REMOTE_REASON_OUTCOME[remoteResult.reason], remoteDetail(remoteResult.reason, projectName, remoteResult.repoUrl, remoteResult.stderr), { code: remoteResult.reason });
850
+ }
575
851
  console.log();
576
852
  if (remoteResult.created) {
577
853
  console.log(chalk.green(' ✓ GitHub remote created and pushed'));
@@ -608,6 +884,12 @@ export async function runNew(projectName, options) {
608
884
  console.log(chalk.dim(` ${remoteResult.stderr.trim()}`));
609
885
  }
610
886
  }
887
+ else if (remoteResult.reason === 'push-timeout') {
888
+ console.log(chalk.yellow(` ⚠ ${remoteDetail('push-timeout', projectName, remoteResult.repoUrl, undefined)}`));
889
+ if (remoteResult.stderr) {
890
+ console.log(chalk.dim(` ${remoteResult.stderr.trim()}`));
891
+ }
892
+ }
611
893
  }
612
894
  // 9. Next steps
613
895
  //
@@ -701,5 +983,75 @@ export async function runNew(projectName, options) {
701
983
  console.log(chalk.dim(` git -C ${outputDir} remote add origin <url>`));
702
984
  console.log();
703
985
  }
986
+ setExitCodeFromSteps(projectName, run);
987
+ }
988
+ /** Exit 1 or 2 when the run's result is fail or could-not-run; leave it alone on a pass. */
989
+ function setExitCodeFromSteps(projectName, run) {
990
+ const code = exitCodeForResult(newProjectDocument({ project: projectName, steps: run.steps }).result);
991
+ if (code !== 0)
992
+ process.exitCode = code;
993
+ }
994
+ /** The step detail and warning text for a `--with-remote` failure reason. */
995
+ export function remoteDetail(reason, projectName, repoUrl, stderr) {
996
+ const tail = stderr ? `: ${stderr.trim()}` : '';
997
+ switch (reason) {
998
+ case 'push-timeout':
999
+ // SF8: the repository may exist whether or not origin was added.
1000
+ return `gh repo create --push was stopped after ${PUSH_TIMEOUT_MS / 1000} s. A repository may already exist on GitHub`
1001
+ + `${repoUrl ? ` at ${repoUrl}` : ''}: run gh repo view ${projectName} to check${tail}`;
1002
+ case 'push-failed':
1003
+ return `the repository was created at ${repoUrl ?? '<url>'} and the push failed${tail}`;
1004
+ case 'gh-failed':
1005
+ return `gh repo create failed; a repository may still exist: run gh repo view ${projectName} to check${tail}`;
1006
+ case 'gh-missing':
1007
+ return 'gh not found; remote setup skipped';
1008
+ case 'gh-version-failed':
1009
+ return 'gh --version failed; remote setup skipped';
1010
+ case 'gh-unauthenticated':
1011
+ return '`gh auth status` failed; remote setup skipped';
1012
+ case 'gh-timed-out':
1013
+ return 'the check of gh timed out; remote setup skipped';
1014
+ }
1015
+ }
1016
+ /**
1017
+ * The end of a `--scaffold-only` run (#1111 items 1 and 2): the optional push,
1018
+ * the footer and the exit code. It never calls `gh`, `runCreate` or
1019
+ * `maybeCreateRemote`.
1020
+ */
1021
+ function finishScaffoldOnly(projectName, outputDir, pushTo, deps, run, configSynced) {
1022
+ let pushed = false;
1023
+ if (pushTo !== undefined) {
1024
+ run.current = 'push';
1025
+ run.url = pushTo;
1026
+ console.log();
1027
+ console.log(chalk.dim(` Pushing main to ${pushTo}...`));
1028
+ const r = (deps.push ?? ((dir, url) => pushToRemote(dir, url)))(outputDir, pushTo);
1029
+ if (r.reason === 'pushed') {
1030
+ pushed = true;
1031
+ console.log(chalk.green(` ✓ pushed main to ${pushTo}`));
1032
+ recordStep(run, 'push', 'pass', r.detail);
1033
+ }
1034
+ else {
1035
+ console.log(chalk.yellow(` ⚠ ${r.reason === 'push-timeout' ? 'the push timed out' : 'the push did not complete'} (${r.reason}): ${r.detail}`));
1036
+ recordStep(run, 'push', PUSH_TO_REASON_OUTCOME[r.reason], r.detail, r.reason);
1037
+ }
1038
+ }
1039
+ console.log();
1040
+ console.log(chalk.green.bold('Project scaffolded (--scaffold-only).'));
1041
+ console.log(chalk.dim('─'.repeat(50)));
1042
+ if (configSynced)
1043
+ console.log(chalk.green(' ✓ Full agent configuration deployed'));
1044
+ console.log(' No team was provisioned and no MemNexus login was needed.');
1045
+ if (pushed)
1046
+ console.log(chalk.dim(` Your code is pushed to ${pushTo}`));
1047
+ console.log();
1048
+ console.log(chalk.bold(' Next steps:'));
1049
+ for (const line of nextStepLines(projectName, null))
1050
+ console.log(line);
1051
+ console.log();
1052
+ setExitCodeFromSteps(projectName, run);
1053
+ }
1054
+ function recordStep(run, name, result, detail, code) {
1055
+ run.steps.push({ name, result, required: true, detail, ...(code ? { code } : {}) });
704
1056
  }
705
1057
  //# sourceMappingURL=new.js.map