@ornexus/neocortex 4.66.0 → 4.66.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 (94) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1206 -1193
  3. package/docs/install/linux-global-install.md +21 -1
  4. package/install.js +22 -28
  5. package/install.ps1 +19 -24
  6. package/install.sh +26 -30
  7. package/package.json +2 -2
  8. package/packages/client/dist/commands/doctor.d.ts +26 -1
  9. package/packages/client/dist/commands/doctor.js +2 -2
  10. package/packages/client/dist/commands/invoke.d.ts +149 -1
  11. package/packages/client/dist/commands/invoke.js +88 -83
  12. package/packages/client/dist/commands/planning-qa.d.ts +57 -0
  13. package/packages/client/dist/commands/planning-qa.js +1 -1
  14. package/packages/client/dist/commands/story-checkpoint.d.ts +2 -0
  15. package/packages/client/dist/commands/story-checkpoint.js +1 -1
  16. package/packages/client/dist/commands/story-worktree.d.ts +1 -1
  17. package/packages/client/dist/commands/story-worktree.js +1 -1
  18. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +51 -0
  19. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -3
  20. package/packages/client/dist/git/epic-lifecycle-evidence.d.ts +184 -0
  21. package/packages/client/dist/git/epic-lifecycle-evidence.js +6 -0
  22. package/packages/client/dist/git/git-lifecycle-store.d.ts +9 -0
  23. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  24. package/packages/client/dist/git/story-worktree-cleanup.js +1 -1
  25. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  26. package/packages/client/dist/git/story-worktree-manager.d.ts +39 -0
  27. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  28. package/packages/client/dist/git/story-write-set-extension.d.ts +62 -0
  29. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  30. package/packages/client/dist/private-execution/codex-executor.d.ts +13 -0
  31. package/packages/client/dist/private-execution/codex-executor.js +4 -4
  32. package/packages/client/dist/private-execution/harness-adapters/antigravity.d.ts +9 -0
  33. package/packages/client/dist/private-execution/harness-adapters/antigravity.js +1 -0
  34. package/packages/client/dist/private-execution/harness-adapters/claude-code.d.ts +8 -0
  35. package/packages/client/dist/private-execution/harness-adapters/claude-code.js +1 -0
  36. package/packages/client/dist/private-execution/harness-adapters/codex.d.ts +7 -0
  37. package/packages/client/dist/private-execution/harness-adapters/codex.js +1 -0
  38. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.d.ts +8 -0
  39. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.js +1 -0
  40. package/packages/client/dist/private-execution/harness-adapters/cursor.d.ts +9 -0
  41. package/packages/client/dist/private-execution/harness-adapters/cursor.js +1 -0
  42. package/packages/client/dist/private-execution/harness-adapters/deepseek.d.ts +9 -0
  43. package/packages/client/dist/private-execution/harness-adapters/deepseek.js +1 -0
  44. package/packages/client/dist/private-execution/harness-adapters/gemini.d.ts +8 -0
  45. package/packages/client/dist/private-execution/harness-adapters/gemini.js +1 -0
  46. package/packages/client/dist/private-execution/harness-adapters/grok.d.ts +9 -0
  47. package/packages/client/dist/private-execution/harness-adapters/grok.js +1 -0
  48. package/packages/client/dist/private-execution/harness-adapters/index.d.ts +73 -0
  49. package/packages/client/dist/private-execution/harness-adapters/index.js +1 -0
  50. package/packages/client/dist/private-execution/harness-adapters/kimi.d.ts +9 -0
  51. package/packages/client/dist/private-execution/harness-adapters/kimi.js +1 -0
  52. package/packages/client/dist/private-execution/harness-adapters/openclaw.d.ts +9 -0
  53. package/packages/client/dist/private-execution/harness-adapters/openclaw.js +1 -0
  54. package/packages/client/dist/private-execution/harness-adapters/opencode.d.ts +7 -0
  55. package/packages/client/dist/private-execution/harness-adapters/opencode.js +1 -0
  56. package/packages/client/dist/private-execution/harness-ephemeral-home.d.ts +19 -0
  57. package/packages/client/dist/private-execution/harness-ephemeral-home.js +1 -0
  58. package/packages/client/dist/private-execution/harness-executor.d.ts +79 -0
  59. package/packages/client/dist/private-execution/harness-executor.js +1 -0
  60. package/packages/client/dist/private-execution/harness-process.d.ts +43 -0
  61. package/packages/client/dist/private-execution/harness-process.js +1 -0
  62. package/packages/client/dist/private-execution/isolated-admission.js +12 -12
  63. package/packages/client/dist/private-execution/isolated-workspace.d.ts +16 -1
  64. package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
  65. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +2 -3
  66. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +7 -4
  67. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -22
  68. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +6 -10
  69. package/packages/client/dist/state/project-state-snapshot.d.ts +10 -0
  70. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  71. package/packages/client/dist/state/structural-dag-projection.d.ts +26 -0
  72. package/packages/client/dist/state/structural-dag-projection.js +1 -1
  73. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +67 -0
  74. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  75. package/packages/shared/dist/compatibility/index.js +28 -0
  76. package/targets-stubs/antigravity/gemini.md +1 -1
  77. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  78. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  79. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  80. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  81. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  82. package/targets-stubs/claude-code/neocortex.md +2 -2
  83. package/targets-stubs/codex/AGENTS.md +1 -1
  84. package/targets-stubs/cursor/agent.md +2 -2
  85. package/targets-stubs/gemini-cli/agent.md +2 -2
  86. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  87. package/targets-stubs/grok/SKILL.md +3 -3
  88. package/targets-stubs/grok/agents/{neocortex.md → neocortex-sentinel.md} +2 -2
  89. package/targets-stubs/grok/install-grok.sh +45 -8
  90. package/targets-stubs/lib/managed-config-merge.js +21 -1
  91. package/targets-stubs/lib/mcp-merge.js +18 -7
  92. package/targets-stubs/opencode/neocortex-root.md +1 -1
  93. package/targets-stubs/opencode/neocortex.md +1 -1
  94. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -12,6 +12,25 @@ permission issues and lists an npm user prefix as the no-sudo fallback. This
12
12
  Neocortex guide follows that order so the default path stays user-owned and does
13
13
  not require root `HOME`.
14
14
 
15
+ ## Default scope on every supported OS
16
+
17
+ The Node launcher, the Bash installer used on Linux/macOS and the PowerShell
18
+ installer used on Windows now default to a global, user-scoped installation.
19
+ They do not prompt for, migrate or create files in the current project.
20
+
21
+ `--skip-project` (`-SkipProject` in direct PowerShell usage) remains accepted for
22
+ automation compatibility, but it is now the default behavior. The historical
23
+ misspelling `--skip-projetct` is also accepted and normalized to the canonical
24
+ flag. Project files are installed only with the explicit opt-in:
25
+
26
+ ```bash
27
+ npx @ornexus/neocortex --targets=codex,claude-code,opencode --create-project
28
+ ```
29
+
30
+ On Windows PowerShell, the equivalent direct installer option is
31
+ `-CreateProject`. Supplying both skip and create options resolves safely to the
32
+ global-only scope.
33
+
15
34
  ## Preferred install paths
16
35
 
17
36
  Prefer a Node version manager first. npm documents this as the recommended way to
@@ -90,7 +109,8 @@ user install works.
90
109
  - `P177_PUBLIC_SAFE_LOG_REDACTED`: installer diagnostics intentionally omitted
91
110
  raw local paths or child output; use the public reason code rather than a raw
92
111
  terminal transcript in support evidence.
93
- - Windows `USERPROFILE` behavior is not changed by this Linux guidance.
112
+ - Windows uses `USERPROFILE` for the same global-by-default scope; project files
113
+ still require `-CreateProject`.
94
114
 
95
115
  If a sanitized npm lifecycle interruption is reported after optional-tool status
96
116
  text, do not assume any third-party tool is part of the default
package/install.js CHANGED
@@ -10,7 +10,7 @@ const path = require('path');
10
10
  const os = require('os');
11
11
  const fs = require('fs');
12
12
  const {
13
- intro, outro, multiselect, confirm, spinner, cancel, isCancel, note, log
13
+ intro, outro, multiselect, spinner, cancel, isCancel, note, log
14
14
  } = require('@clack/prompts');
15
15
  const color = require('picocolors');
16
16
 
@@ -156,6 +156,7 @@ const FLAG_MAP_WIN32 = {
156
156
  // Skip project directory creation
157
157
  '-s': '-SkipProject',
158
158
  '--skip-project': '-SkipProject',
159
+ '--skip-projetct': '-SkipProject',
159
160
  // Force project directory creation
160
161
  '--create-project': '-CreateProject',
161
162
  // Suppress non-essential output
@@ -200,6 +201,15 @@ function mapArgs(platform, originalArgs) {
200
201
  return filtered;
201
202
  }
202
203
 
204
+ function hasSkipProjectFlag(originalArgs) {
205
+ return originalArgs.some(arg => ['-s', '--skip-project', '--skip-projetct', '-SkipProject', '-SkipProjetct'].includes(arg));
206
+ }
207
+
208
+ function shouldCreateProject(originalArgs) {
209
+ return !hasSkipProjectFlag(originalArgs)
210
+ && (originalArgs.includes('--create-project') || originalArgs.includes('-CreateProject'));
211
+ }
212
+
203
213
  // ═══════════════════════════════════════════════════════════════════
204
214
  // SCRIPT EXECUTION
205
215
  // ═══════════════════════════════════════════════════════════════════
@@ -309,8 +319,8 @@ function showHelp() {
309
319
  console.log(color.dim(' Opcoes:'));
310
320
  console.log(` ${color.cyan('-y, --yes')} Modo automatico (Claude Code only)`);
311
321
  console.log(` ${color.cyan('--targets=<lista>')} Plataformas separadas por virgula`);
312
- console.log(` ${color.cyan('--create-project')} Instalar estrutura no projeto`);
313
- console.log(` ${color.cyan('-s, --skip-project')} Nao perguntar sobre projeto`);
322
+ console.log(` ${color.cyan('--create-project')} Instalar estrutura no projeto (opt-in)`);
323
+ console.log(` ${color.cyan('-s, --skip-project')} Instalacao somente global (padrao)`);
314
324
  console.log(` ${color.cyan('-q, --quiet')} Modo silencioso`);
315
325
  console.log(` ${color.cyan('--dry-run')} Mostra adapters/stubs resolvidos sem modificar arquivos`);
316
326
  console.log(` ${color.cyan('--cleanup-legacy')} Remover artefatos legados de ~/.claude/`);
@@ -390,23 +400,7 @@ async function interactiveWizard() {
390
400
  });
391
401
  log.info(`Plataformas: ${color.bold(selectedNames.join(', '))}`);
392
402
 
393
- // Ask about project-level installation
394
- let createProject = false;
395
- if (!args.includes('-s') && !args.includes('--skip-project')) {
396
- const projectInstall = await confirm({
397
- message: 'Instalar estrutura completa no diretorio atual do projeto?',
398
- initialValue: false,
399
- });
400
-
401
- if (isCancel(projectInstall)) {
402
- cancel('Instalacao cancelada.');
403
- process.exit(0);
404
- }
405
-
406
- createProject = projectInstall;
407
- }
408
-
409
- return { selectedPlatforms, createProject };
403
+ return { selectedPlatforms, createProject: shouldCreateProject(args) };
410
404
  }
411
405
 
412
406
  // ═══════════════════════════════════════════════════════════════════
@@ -542,7 +536,7 @@ async function main() {
542
536
 
543
537
  // Determine selected targets
544
538
  let selectedTargets = null;
545
- let createProject = false;
539
+ let createProject = shouldCreateProject(args);
546
540
 
547
541
  // Priority 1: --targets= argument
548
542
  const targetsArg = parseTargetsArg();
@@ -557,13 +551,10 @@ async function main() {
557
551
  }
558
552
  selectedTargets = targetsArg;
559
553
 
560
- // In non-interactive mode with explicit targets, still check for project flag
561
- if (args.includes('--create-project')) createProject = true;
562
554
  }
563
555
  // Priority 2: --yes flag = Claude Code only (backward compat)
564
556
  else if (isAutoYes()) {
565
557
  selectedTargets = ['claude-code'];
566
- createProject = true;
567
558
  }
568
559
  // Priority 3: Interactive selection (if TTY)
569
560
  else if (process.stdin.isTTY && process.stdout.isTTY) {
@@ -611,10 +602,11 @@ async function main() {
611
602
  }
612
603
 
613
604
  // Dispatch to platform-specific installer
614
- if (createProject) {
615
- args.push('--create-project');
616
- } else if (!args.includes('-s') && !args.includes('--skip-project')) {
617
- args.push('--skip-project');
605
+ if (!createProject) {
606
+ for (let index = args.length - 1; index >= 0; index -= 1) {
607
+ if (args[index] === '--create-project' || args[index] === '-CreateProject') args.splice(index, 1);
608
+ }
609
+ if (!hasSkipProjectFlag(args)) args.push('--skip-project');
618
610
  }
619
611
 
620
612
  // Suppress shell banner when JS wizard already showed it (avoid duplicate)
@@ -642,4 +634,6 @@ module.exports = {
642
634
  canonicalizeTargets,
643
635
  parseTargetsArg,
644
636
  stripTargetsArgs,
637
+ hasSkipProjectFlag,
638
+ shouldCreateProject,
645
639
  };
package/install.ps1 CHANGED
@@ -4,6 +4,7 @@
4
4
  param(
5
5
  [switch]$Yes,
6
6
  [switch]$Debug,
7
+ [Alias("SkipProjetct")]
7
8
  [switch]$SkipProject,
8
9
  [switch]$CreateProject,
9
10
  [switch]$Quiet,
@@ -17,7 +18,7 @@ param(
17
18
  [string]$ServerUrl = ('https://{0}.{1}.{2}' -f 'api','neocortex','sh')
18
19
  )
19
20
 
20
- $VERSION = "4.66.0"
21
+ $VERSION = "4.66.2"
21
22
 
22
23
  # =============================================================================
23
24
  # CONFIGURACOES
@@ -32,7 +33,7 @@ $script:LegacyWarnings = 0
32
33
 
33
34
  $AUTO_YES = $Yes
34
35
  $DEBUG_MODE = $Debug
35
- $SKIP_PROJECT_DIRS = $SkipProject
36
+ $SKIP_PROJECT_DIRS = $SkipProject -or (-not $CreateProject)
36
37
  $QUIET_MODE = $Quiet
37
38
  $NO_BANNER = $NoBanner
38
39
  $NEOCORTEX_SERVER_URL = $ServerUrl
@@ -63,8 +64,8 @@ if ($Help) {
63
64
  Write-Host " Opcoes:" -ForegroundColor DarkGray
64
65
  Write-Host " -Yes Modo automatico (Claude Code only)" -ForegroundColor Cyan
65
66
  Write-Host " -Targets <lista> Plataformas separadas por virgula" -ForegroundColor Cyan
66
- Write-Host " -CreateProject Instalar estrutura no projeto" -ForegroundColor Cyan
67
- Write-Host " -SkipProject Nao perguntar sobre projeto" -ForegroundColor Cyan
67
+ Write-Host " -CreateProject Instalar estrutura no projeto (opt-in)" -ForegroundColor Cyan
68
+ Write-Host " -SkipProject Instalacao somente global (padrao)" -ForegroundColor Cyan
68
69
  Write-Host " -Quiet Modo silencioso" -ForegroundColor Cyan
69
70
  Write-Host " -DryRun Mostra adapters/stubs resolvidos sem modificar arquivos" -ForegroundColor Cyan
70
71
  Write-Host " -CleanupLegacy (Redundante) Limpeza agora e automatica" -ForegroundColor Cyan
@@ -450,7 +451,9 @@ function Invoke-ExistingProjectAgentRoleMigration {
450
451
  function Show-AgentRoleMigrationPlan {
451
452
  param([string[]]$TargetList)
452
453
  if (-not $DryRun) { return }
453
- Invoke-ExistingProjectAgentRoleMigration -ProjectDir (Get-Location).Path -TargetList $TargetList
454
+ if ((-not $SKIP_PROJECT_DIRS) -and $CreateProject) {
455
+ Invoke-ExistingProjectAgentRoleMigration -ProjectDir (Get-Location).Path -TargetList $TargetList
456
+ }
454
457
  foreach ($target in $TargetList) {
455
458
  switch ($target) {
456
459
  "claude-code" {
@@ -1851,19 +1854,7 @@ function Install-Targets {
1851
1854
  # =============================================================================
1852
1855
 
1853
1856
  function New-ProjectDirectories {
1854
- if ($QUIET_MODE -or $SKIP_PROJECT_DIRS) { return }
1855
-
1856
- $shouldCreate = $false
1857
-
1858
- if ($CreateProject -or $AUTO_YES) {
1859
- $shouldCreate = $true
1860
- } else {
1861
- Write-Host " Instalar estrutura no projeto atual? [s/N]: " -NoNewline -ForegroundColor White
1862
- $response = Read-HostWithTimeout -TimeoutSeconds 30 -Default "n"
1863
- if ($response -match "^[sS]([iI][mM]?)?$|^[yY]([eE][sS]?)?$") { $shouldCreate = $true }
1864
- }
1865
-
1866
- if (-not $shouldCreate) { return }
1857
+ if ($SKIP_PROJECT_DIRS -or (-not $CreateProject)) { return }
1867
1858
 
1868
1859
  $projectDir = Get-Location
1869
1860
 
@@ -2220,8 +2211,10 @@ Install-Skills | Out-Null
2220
2211
 
2221
2212
  # Step 4: Targets
2222
2213
  Write-Step 4 $totalSteps "Instalando $($script:SelectedTargets.Count) plataforma(s)"
2223
- # P228.19 AM-05: existing project role profiles migrate before the user scope.
2224
- Invoke-ExistingProjectAgentRoleMigration -ProjectDir (Get-Location).Path -TargetList $script:SelectedTargets
2214
+ # Project state is opt-in. A default/global install never mutates the CWD.
2215
+ if ((-not $SKIP_PROJECT_DIRS) -and $CreateProject) {
2216
+ Invoke-ExistingProjectAgentRoleMigration -ProjectDir (Get-Location).Path -TargetList $script:SelectedTargets
2217
+ }
2225
2218
  Install-Targets -TargetList $script:SelectedTargets
2226
2219
 
2227
2220
  # Step 5: Claude Code extras
@@ -2237,10 +2230,12 @@ $verifySuccess = Verify-Installation
2237
2230
  $installSuccess = $installSuccess -and $verifySuccess
2238
2231
 
2239
2232
  if (Show-Result $installSuccess) {
2240
- $projectSources = Test-ProjectMigrationNeeds
2241
- if ($projectSources) {
2242
- Write-Warn "Migracao detectada"
2243
- Write-Info "Execute: neocortex-client refresh-memory --project-root . para atualizar a memoria do projeto"
2233
+ if ((-not $SKIP_PROJECT_DIRS) -and $CreateProject) {
2234
+ $projectSources = Test-ProjectMigrationNeeds
2235
+ if ($projectSources) {
2236
+ Write-Warn "Migracao detectada"
2237
+ Write-Info "Execute: neocortex-client refresh-memory --project-root . para atualizar a memoria do projeto"
2238
+ }
2244
2239
  }
2245
2240
  New-ProjectDirectories
2246
2241
  Write-Host " Desenvolvido por OrNexus Team" -ForegroundColor DarkGray
package/install.sh CHANGED
@@ -4,7 +4,7 @@
4
4
  # Development Orchestrator
5
5
 
6
6
  # Versao do instalador
7
- VERSION="4.66.0"
7
+ VERSION="4.66.2"
8
8
 
9
9
  # Flags
10
10
  MIGRATION_DETECTED=false
@@ -43,7 +43,8 @@ fi
43
43
 
44
44
  AUTO_YES=false
45
45
  DEBUG_MODE=false
46
- SKIP_PROJECT_DIRS=false
46
+ SKIP_PROJECT_DIRS=true
47
+ PROJECT_SKIP_EXPLICIT=false
47
48
  CREATE_PROJECT=false
48
49
  QUIET_MODE=false
49
50
  NO_BANNER=false
@@ -54,7 +55,7 @@ while [[ $# -gt 0 ]]; do
54
55
  case $1 in
55
56
  -y|--yes) AUTO_YES=true; shift ;;
56
57
  -d|--debug) DEBUG_MODE=true; shift ;;
57
- -s|--skip-project) SKIP_PROJECT_DIRS=true; shift ;;
58
+ -s|--skip-project|--skip-projetct) PROJECT_SKIP_EXPLICIT=true; shift ;;
58
59
  -q|--quiet) QUIET_MODE=true; shift ;;
59
60
  --dry-run) DRY_RUN=true; shift ;;
60
61
  --no-banner) NO_BANNER=true; shift ;;
@@ -73,8 +74,8 @@ while [[ $# -gt 0 ]]; do
73
74
  echo " Opcoes:"
74
75
  echo " -y, --yes Modo automatico (Claude Code only)"
75
76
  echo " --targets=<lista> Plataformas separadas por virgula"
76
- echo " --create-project Instalar estrutura no projeto"
77
- echo " -s, --skip-project Nao perguntar sobre projeto"
77
+ echo " --create-project Instalar estrutura no projeto (opt-in)"
78
+ echo " -s, --skip-project Instalacao somente global (padrao)"
78
79
  echo " -q, --quiet Modo silencioso"
79
80
  echo " --dry-run Mostra adapters/stubs resolvidos sem modificar arquivos"
80
81
  echo " --cleanup-legacy (Redundante) Limpeza agora e automatica"
@@ -90,6 +91,13 @@ while [[ $# -gt 0 ]]; do
90
91
  esac
91
92
  done
92
93
 
94
+ if [ "$PROJECT_SKIP_EXPLICIT" = true ]; then
95
+ SKIP_PROJECT_DIRS=true
96
+ CREATE_PROJECT=false
97
+ elif [ "$CREATE_PROJECT" = true ]; then
98
+ SKIP_PROJECT_DIRS=false
99
+ fi
100
+
93
101
  if ! is_interactive; then
94
102
  AUTO_YES=true
95
103
  fi
@@ -632,7 +640,9 @@ plan_agent_role_migration() {
632
640
  local targets="$1" target
633
641
  [ "$DRY_RUN" = true ] || return 0
634
642
  command -v node >/dev/null 2>&1 || return 0
635
- migrate_existing_project_agent_roles "$PWD" "$targets"
643
+ if [ "$CREATE_PROJECT" = true ]; then
644
+ migrate_existing_project_agent_roles "$PWD" "$targets"
645
+ fi
636
646
  for target in $(echo "$targets" | tr ',' ' '); do
637
647
  case "$target" in
638
648
  claude-code)
@@ -1081,7 +1091,7 @@ show_target_resolution_dry_run() {
1081
1091
  ;;
1082
1092
  grok)
1083
1093
  info "Dry-run Skill target=grok file=${GROK_HOME:-$HOME/.grok}/skills/neocortex/SKILL.md project=.grok/skills/neocortex/SKILL.md"
1084
- info "Dry-run Agent target=grok file=${GROK_HOME:-$HOME/.grok}/agents/neocortex.md project=.grok/agents/neocortex.md action=managed-non-overwrite"
1094
+ info "Dry-run Agent target=grok file=${GROK_HOME:-$HOME/.grok}/agents/neocortex-sentinel.md project=.grok/agents/neocortex-sentinel.md action=managed-non-overwrite legacy=retire-if-managed-hash"
1085
1095
  info "Dry-run MCP target=grok file=${GROK_HOME:-$HOME/.grok}/config.toml root=mcp_servers managed=playwright,browser_use,figma,shadcn,chrome-devtools action=replace-managed-sections-preserve-unknown"
1086
1096
  ;;
1087
1097
  opencode)
@@ -1887,28 +1897,10 @@ show_result() {
1887
1897
  # =============================================================================
1888
1898
 
1889
1899
  create_project_dirs() {
1890
- [ "$QUIET_MODE" = true ] && return
1891
1900
  [ "$SKIP_PROJECT_DIRS" = true ] && return
1901
+ [ "$CREATE_PROJECT" != true ] && return
1892
1902
 
1893
- local should_create=false
1894
-
1895
- if [ "$CREATE_PROJECT" = true ] || [ "$AUTO_YES" = true ]; then
1896
- should_create=true
1897
- else
1898
- echo -ne " Instalar estrutura no projeto atual? ${BOLD}[s/N]:${NC} "
1899
-
1900
- local response="n"
1901
- if read -r -t 30 response </dev/tty 2>/dev/null; then
1902
- :
1903
- else
1904
- echo ""
1905
- response="n"
1906
- fi
1907
-
1908
- [[ "$response" =~ ^([sS][iI]?[mM]?|[yY][eE]?[sS]?)$ ]] && should_create=true
1909
- fi
1910
-
1911
- if [ "$should_create" = true ]; then
1903
+ if [ "$CREATE_PROJECT" = true ]; then
1912
1904
  local project_dir="$PWD"
1913
1905
 
1914
1906
  if is_neocortex_source_project "$project_dir"; then
@@ -2280,8 +2272,10 @@ main() {
2280
2272
 
2281
2273
  # Step 4: Targets
2282
2274
  step 4 $TOTAL_STEPS "Instalando ${BOLD}$target_count${NC} plataforma(s)"
2283
- # P228.19 AM-05: existing project role profiles migrate before the user scope.
2284
- migrate_existing_project_agent_roles "$PWD" "$SELECTED_TARGETS"
2275
+ # Project state is opt-in. A default/global install never mutates the CWD.
2276
+ if [ "$CREATE_PROJECT" = true ]; then
2277
+ migrate_existing_project_agent_roles "$PWD" "$SELECTED_TARGETS"
2278
+ fi
2285
2279
  install_targets "$SELECTED_TARGETS"
2286
2280
 
2287
2281
  # Step 5: Claude Code extras
@@ -2297,7 +2291,9 @@ main() {
2297
2291
  local result_code=$?
2298
2292
 
2299
2293
  if [ $result_code -eq 0 ]; then
2300
- show_migration_info
2294
+ if [ "$CREATE_PROJECT" = true ]; then
2295
+ show_migration_info
2296
+ fi
2301
2297
  create_project_dirs
2302
2298
  echo -e " ${DIM}Desenvolvido por OrNexus Team${NC}"
2303
2299
  echo ""
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ornexus/neocortex",
3
- "version": "4.66.0",
4
- "description": "Neocortex v4.66.0",
3
+ "version": "4.66.2",
4
+ "description": "Neocortex v4.66.2",
5
5
  "keywords": [
6
6
  "claude",
7
7
  "claude-code",
@@ -7,6 +7,8 @@
7
7
  * integrated in parallel.
8
8
  */
9
9
  import { type ClaudeWorktreeBaseRefState } from '../agent/claude-worktree-base.js';
10
+ import { type PrivateExecutionHostKind } from '../../../shared/dist/compatibility/index.js';
11
+ import { type PrivateHarnessExecutorPortOptions } from '../private-execution/harness-adapters/index.js';
10
12
  export declare const DOCTOR_SCHEMA_VERSION: "CompatibilityReleaseDoctor/1.0";
11
13
  export declare const DOCTOR_RESPONSE_SCHEMA_VERSION: "CompatibilityDoctorResponse/1.0";
12
14
  export declare const DOCTOR_EXIT_CODES: Readonly<{
@@ -80,7 +82,21 @@ export interface DoctorReport {
80
82
  readonly dimensions: Readonly<Record<ReleaseDimensionName, DoctorReleaseDimension>>;
81
83
  };
82
84
  readonly findings: readonly DoctorFinding[];
85
+ /** P229.03 (CON-P229.03-DOCTOR): additive; never affects `overall`/`exitCode`. */
86
+ readonly privateExecutors: readonly DoctorPrivateExecutorStatus[];
83
87
  }
88
+ /** P229.03 (DEC-4): per-host private executor status, enums and versions only. */
89
+ /** `not-probed`: library call without an injected probe; no process is spawned (hermetic). */
90
+ export type DoctorPrivateExecutorAvailability = 'available' | 'absent' | 'refused' | 'not-probed';
91
+ export interface DoctorPrivateExecutorProbeResult {
92
+ readonly availability: DoctorPrivateExecutorAvailability;
93
+ readonly version: string | null;
94
+ readonly refusalReasonCode: string | null;
95
+ }
96
+ export interface DoctorPrivateExecutorStatus extends DoctorPrivateExecutorProbeResult {
97
+ readonly hostKind: PrivateExecutionHostKind;
98
+ }
99
+ export type DoctorPrivateExecutorProbe = (hostKind: PrivateExecutionHostKind) => Promise<DoctorPrivateExecutorProbeResult>;
84
100
  interface CompatibilityAuthority {
85
101
  readonly createCompatibilityOffer: (input: {
86
102
  readonly clientVersion: string;
@@ -113,6 +129,8 @@ export interface DoctorDependencies {
113
129
  readonly env?: Readonly<Record<string, string | undefined>>;
114
130
  readonly stdout?: (message: string) => void;
115
131
  readonly stderr?: (message: string) => void;
132
+ /** P229.03 (DEC-4): injectable per-host private executor probe. */
133
+ readonly probePrivateExecutor?: DoctorPrivateExecutorProbe;
116
134
  }
117
135
  interface ParsedDoctorArgs {
118
136
  readonly mode: DoctorMode;
@@ -133,7 +151,14 @@ export declare function loadSharedCompatibilityAuthority(): Promise<Compatibilit
133
151
  export declare function collectLocalReleaseLifecycleContext(projectRoot: string, authority: CompatibilityAuthority): unknown | null;
134
152
  /** Test seam: replace the host settings inspector; returns the previous one. */
135
153
  export declare function __setDoctorClaudeWorktreeInspector(next: () => ClaudeWorktreeBaseRefState): () => ClaudeWorktreeBaseRefState;
154
+ /**
155
+ * P229.03 (DEC-4) default probe: declared refusal -> `refused`; otherwise the
156
+ * port preflight (`--version` under the core timeout). Headless-unavailable
157
+ * -> `absent`, version-unsupported -> `refused`, any other error -> `absent`.
158
+ * Never throws and never returns paths, argv or stdout.
159
+ */
160
+ export declare function defaultProbePrivateExecutor(hostKind: string, options?: PrivateHarnessExecutorPortOptions): Promise<DoctorPrivateExecutorProbeResult>;
136
161
  export declare function runDoctor(options: ParsedDoctorArgs, dependencies?: DoctorDependencies): Promise<DoctorReport>;
137
162
  export declare function renderDoctorReport(report: DoctorReport): string;
138
- export declare function doctorCliHandler(args: readonly string[], dependencies?: DoctorDependencies): Promise<number>;
163
+ export declare function doctorCliHandler(args: readonly string[], injected?: DoctorDependencies): Promise<number>;
139
164
  export {};
@@ -1,2 +1,2 @@
1
- import{Buffer as L}from"node:buffer";import{createHash as k}from"node:crypto";import{execFileSync as P}from"node:child_process";import{readFileSync as Y,statSync as G}from"node:fs";import{join as K,resolve as W}from"node:path";import{COMMAND_REGISTRY_CHECKSUM as A,COMMAND_REGISTRY_VERSION as C}from"../generated/command-registry.generated.js";import{DEFAULT_SERVER_URL as z}from"../constants.js";import{getClientVersion as J}from"../version.js";import{inspectClaudeWorktreeBaseRef as Z}from"../agent/claude-worktree-base.js";const X="CompatibilityReleaseDoctor/1.0",Q="CompatibilityDoctorResponse/1.0",I=Object.freeze({SUCCESS:0,BLOCKED:1,USAGE:2}),n=Object.freeze({HEALTHY:"doctor-healthy",OFFLINE:"doctor-offline",SERVER_UNREACHABLE:"server-unreachable",CLIENT_TOO_OLD:"client-too-old",SERVER_TOO_OLD:"server-too-old",PROTOCOL_MISMATCH:"protocol-mismatch",SCHEMA_MISMATCH:"schema-mismatch",CAPABILITY_MISMATCH:"capability-mismatch",REGISTRY_DRIFT:"registry-drift",MALFORMED_RESPONSE:"malformed-response",AUTHORITY_UNAVAILABLE:"compatibility-authority-unavailable",RELEASE_LIFECYCLE_UNAVAILABLE:"release-lifecycle-unavailable",REQUIRED_DIMENSION_BLOCKED:"required-release-dimension-blocked",CLAUDE_WORKTREE_BASEREF_NOT_HEAD:"claude-worktree-baseref-not-head"}),v=Object.freeze(["implementationComplete","betaOperable","releaseReady","productionPromoted"]),ee=64*1024,re=32,te=5e3,U=/^[a-z][a-z0-9-]{0,63}$/u,D=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,79}$/u,g=/^\d{1,6}\.\d{1,6}\.\d{1,6}(?:[-+][A-Za-z0-9.-]{1,40})?$/u,ie=/^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/u,F=/^[a-f0-9]{64}$/u,oe=/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/u,ne=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u,se=/^(?:local-gate|beta-receipt|release-gate|promotion-receipt|sha256):[a-f0-9]{64}$/u,l=Object.freeze({healthy:"No compatibility remediation is required.",offline:"Rerun without --offline when read-only server evidence is available.",unreachable:"Check read-only server reachability, then rerun doctor.",clientTooOld:"Run a separately authorized client update, then rerun doctor.",serverTooOld:"Ask an authorized server operator to update the server, then rerun doctor.",protocol:"Align client and server protocol releases before invoking protected operations.",schema:"Use a client and server pair that supports the required public schemas.",capability:"Enable no feature here; use a release pair with the required capability set.",registry:"Install an exact release pair with the same command-registry checksum.",malformed:"Contact support with the reason code only; do not attach raw response data.",authority:"Integrate the P223.01 shared compatibility authority, then rerun doctor.",lifecycle:"Obtain bounded physical release evidence through separately authorized operations.",required:"Satisfy and verify the required physical release dimension through a separately authorized operation.",claudeWorktree:'Set Claude Code worktree.baseRef to "head" in ~/.claude/settings.json (neocortex refresh adds it when absent) so v4 story worktrees start from the epic checkout.'}),x=new Map([[n.MALFORMED_RESPONSE,0],[n.AUTHORITY_UNAVAILABLE,1],[n.CLIENT_TOO_OLD,2],[n.SERVER_TOO_OLD,3],[n.PROTOCOL_MISMATCH,4],[n.SCHEMA_MISMATCH,5],[n.CAPABILITY_MISMATCH,6],[n.REGISTRY_DRIFT,7],[n.SERVER_UNREACHABLE,8],[n.OFFLINE,9],[n.RELEASE_LIFECYCLE_UNAVAILABLE,10],[n.REQUIRED_DIMENSION_BLOCKED,11],[n.HEALTHY,100]]);function q(e="release-evidence-unavailable"){const r=()=>Object.freeze({value:"unknown",freshness:"unknown",reasonCodes:Object.freeze([e]),evidenceRefs:Object.freeze([])});return Object.freeze({implementationComplete:r(),betaOperable:r(),releaseReady:r(),productionPromoted:r()})}function ae(e){const r=Object.freeze({implementation:"implementationComplete","implementation-complete":"implementationComplete",beta:"betaOperable","beta-operable":"betaOperable",release:"releaseReady","release-ready":"releaseReady",production:"productionPromoted","production-promoted":"productionPromoted"});return e?r[e]??null:null}function ce(e,r=process.env){let t="online",i=!1,o=r.NEOCORTEX_SERVER_URL??z,c=!1,u=null,f=process.cwd();for(let a=0;a<e.length;a+=1){const s=e[a];if(s==="--offline")t="offline";else if(s==="--json")i=!0;else if(s==="--server-url"){const p=e[a+1];if(!p)throw new Error("doctor-server-url-required");o=p,c=!0,a+=1}else if(s==="--require"){const p=e[a+1],m=ae(p);if(!p||!m)throw new Error("doctor-required-dimension-invalid");u=m,a+=1}else if(s==="--project-root"){const p=e[a+1];if(!p||p.length>4096||p.includes("\0"))throw new Error("doctor-project-root-invalid");f=W(p),a+=1}else throw new Error("doctor-argument-invalid")}if(t==="offline"&&c)throw new Error("doctor-offline-server-url-conflict");if(t==="offline")return Object.freeze({mode:t,json:i,serverUrl:z,requiredDimension:u,projectRoot:f});if(o.length>2048)throw new Error("doctor-server-url-invalid");try{const a=new URL(o);if(a.protocol!=="http:"&&a.protocol!=="https:"||a.username||a.password||a.search||a.hash)throw new Error("url")}catch{throw new Error("doctor-server-url-invalid")}return Object.freeze({mode:t,json:i,serverUrl:o.replace(/\/+$/u,""),requiredDimension:u,projectRoot:f})}function le(e){if(!e||typeof e!="object")return!1;const r=e;return typeof r.createCompatibilityOffer=="function"&&typeof r.isCompatibilityResultV1=="function"&&typeof r.validateReleaseLifecycle=="function"}async function de(){const e=["@neocortex/shared/compatibility","../../../shared/dist/compatibility/index.js"];for(const r of e)try{const t=await import(r);if(le(t))return t}catch{}return null}function ue(e,r){if(typeof r.createReleaseLifecycleContext!="function")return null;try{const t=K(e,".neocortex","state.json"),i=G(t);if(!i.isFile()||i.size<=0||i.size>1024*1024)return null;const o=JSON.parse(Y(t,"utf8")),u=(o.config&&typeof o.config=="object"&&!Array.isArray(o.config)?o.config:o.project&&typeof o.project=="object"&&!Array.isArray(o.project)?o.project:null)?.project_id;if(typeof u!="string"||!oe.test(u))return null;const f=P("git",["rev-parse","--verify","HEAD"],{cwd:e,encoding:"utf8",timeout:2e3,maxBuffer:1024,stdio:["ignore","pipe","ignore"]}).trim().toLowerCase();if(!ne.test(f))return null;const a=k("sha256").update("git-lineage-v1\0").update(f).digest("hex"),s=`candidate-${k("sha256").update("release-candidate-v1\0").update(u).update("\0").update(f).digest("hex").slice(0,32)}`;return r.createReleaseLifecycleContext({projectId:u,candidateId:s,lineageSha256:a})}catch{return null}}function d(e,r,t,i,o=null){return Object.freeze({severity:e,reasonCode:r,affectedDimension:t,evidenceRef:o,remediation:i})}function fe(e,r){if(!g.test(e)||!g.test(r))return null;const t=c=>c.split(/[-+]/u,1)[0].split(".").map(Number),i=t(e),o=t(r);for(let c=0;c<3;c+=1)if(i[c]!==o[c])return i[c]<o[c]?-1:1;return 0}function S(e){return Object.freeze([...new Set(e.filter(r=>U.test(r)))].slice(0,8).sort())}function H(e){return Object.freeze([...new Set(e.filter(r=>D.test(r)))].slice(0,32).sort())}function $(e){return Object.freeze([...new Set(e.filter(r=>se.test(r)))].slice(0,8).sort())}function me(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e,t=r.commandRegistry;return!["compatible","degraded","incompatible"].includes(String(r.status))||typeof r.clientVersion!="string"||!g.test(r.clientVersion)||typeof r.serverVersion!="string"||!g.test(r.serverVersion)||!(r.protocolVersion===null||typeof r.protocolVersion=="string"&&D.test(r.protocolVersion))||!Array.isArray(r.schemaVersions)||!r.schemaVersions.every(i=>typeof i=="string")||!Array.isArray(r.capabilityIds)||!r.capabilityIds.every(i=>typeof i=="string")||!Array.isArray(r.reasonCodes)||!r.reasonCodes.every(i=>typeof i=="string")||!t||typeof t.version!="string"||!ie.test(t.version)||typeof t.checksum!="string"||!F.test(t.checksum)||!["matched","mismatched","unknown"].includes(String(t.status))?null:r}function pe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e;if(typeof r.candidateId!="string"||!D.test(r.candidateId)||typeof r.lineageSha256!="string"||!F.test(r.lineageSha256))return null;for(const t of v){const i=r[t];if(!i||typeof i!="object"||Array.isArray(i))return null;const o=i;if(!(typeof o.value=="boolean"||o.value==="unknown")||!["fresh","stale","unknown"].includes(String(o.freshness))||!Array.isArray(o.reasonCodes)||!o.reasonCodes.every(c=>typeof c=="string")||!Array.isArray(o.evidenceRefs)||!o.evidenceRefs.every(c=>typeof c=="string"))return null}return r}function ye(e){const r={error:0,warning:1,info:2},t=new Map([["compatibility",0],["releaseLifecycle",1],["implementationComplete",2],["betaOperable",3],["releaseReady",4],["productionPromoted",5]]);return Object.freeze([...e].sort((i,o)=>r[i.severity]-r[o.severity]||(x.get(i.reasonCode)??50)-(x.get(o.reasonCode)??50)||(t.get(i.affectedDimension)??99)-(t.get(o.affectedDimension)??99)||i.reasonCode.localeCompare(o.reasonCode)).slice(0,re))}function Ee(e){return Object.freeze({status:"unknown",clientVersion:e,serverVersion:null,protocolVersion:null,schemaVersions:Object.freeze([]),capabilityIds:Object.freeze([]),registry:Object.freeze({localVersion:C,localChecksum:A,remoteVersion:null,remoteChecksum:null,status:"unknown"})})}let T=()=>Z();function Ne(e){const r=T;return T=e,r}function he(){let e;try{e=T()}catch{e="unknown"}return e==="absent"||e==="user-value"||e==="settings-invalid"?[d("warning",n.CLAUDE_WORKTREE_BASEREF_NOT_HEAD,"compatibility",l.claudeWorktree,null)]:[]}function E(e){const r=[...e.findings,...he()],t=e.dimensions??q();let i=e.incompatible;e.requiredDimension&&t[e.requiredDimension].value!==!0&&(i=!0,r.push(d("error",n.REQUIRED_DIMENSION_BLOCKED,e.requiredDimension,l.required,t[e.requiredDimension].evidenceRefs[0]??null)));const o=ye(r),c=i?"incompatible":o.some(u=>u.severity==="warning")?"degraded":"healthy";return Object.freeze({schemaVersion:X,publicSafe:!0,readOnly:!0,mode:e.mode,overall:c,exitCode:i?I.BLOCKED:I.SUCCESS,compatibility:e.compatibility??Ee(e.clientVersion),release:Object.freeze({candidateId:e.candidateId??null,lineageSha256:e.lineageSha256??null,requiredDimension:e.requiredDimension,dimensions:t}),findings:o})}function be(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e;return"compatibility"in r?r.schemaVersion!==void 0&&r.schemaVersion!==Q?null:{compatibility:r.compatibility,...r.releaseLifecycle!==void 0?{releaseLifecycle:r.releaseLifecycle}:{}}:{compatibility:e}}async function Re(e,r,t,i){const o=new AbortController,c=setTimeout(()=>o.abort(),te);try{const u=L.from(JSON.stringify(t),"utf8").toString("base64url");if(u.length>8192)return{kind:"malformed"};const f=i===null?null:L.from(JSON.stringify(i),"utf8").toString("base64url");if(f&&f.length>2048)return{kind:"malformed"};const a=await e(`${r}/api/v1/compatibility`,{method:"GET",headers:Object.freeze({Accept:"application/json","Cache-Control":"no-store","X-Neocortex-Compatibility-Offer":u,...f?{"X-Neocortex-Release-Context":f}:{}}),signal:o.signal});if(a.status===404||a.status===405||a.status===426)return{kind:"server-too-old"};if(!a.ok)return a.status>=500?{kind:"unreachable"}:{kind:"malformed"};const s=await a.text();if(L.byteLength(s,"utf8")>ee)return{kind:"malformed"};try{return{kind:"ok",value:JSON.parse(s)}}catch{return{kind:"malformed"}}}catch{return{kind:"unreachable"}}finally{clearTimeout(c)}}function Oe(e,r){return E({mode:"offline",clientVersion:e,requiredDimension:r,incompatible:!1,findings:[d("warning",n.OFFLINE,"compatibility",l.offline),d("warning",n.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]})}async function Ae(e,r={}){const t=(r.getClientVersion??J)();if(e.mode==="offline")return Oe(t,e.requiredDimension);const i=await(r.loadCompatibilityAuthority??de)();if(!i)return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.AUTHORITY_UNAVAILABLE,"compatibility",l.authority)]});let o;try{o=i.createCompatibilityOffer({clientVersion:t,registryVersion:C,registryChecksum:A})}catch{return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.AUTHORITY_UNAVAILABLE,"compatibility",l.authority)]})}const c=(r.collectReleaseContext??ue)(e.projectRoot,i),u=r.fetch??globalThis.fetch,f=await Re(u,e.serverUrl,o,c);if(f.kind==="unreachable")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!1,findings:[d("warning",n.SERVER_UNREACHABLE,"compatibility",l.unreachable),d("warning",n.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]});if(f.kind==="server-too-old")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.SERVER_TOO_OLD,"compatibility",l.serverTooOld),d("warning",n.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]});if(f.kind==="malformed")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const a=be(f.value);if(!a||!i.isCompatibilityResultV1(a.compatibility))return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const s=me(a.compatibility);if(!s||s.clientVersion!==t)return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[d("error",n.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const p=Object.freeze({status:s.status,clientVersion:t,serverVersion:s.serverVersion,protocolVersion:s.protocolVersion,schemaVersions:H(s.schemaVersions),capabilityIds:H(s.capabilityIds),registry:Object.freeze({localVersion:C,localChecksum:A,remoteVersion:s.commandRegistry.version,remoteChecksum:s.commandRegistry.checksum,status:s.commandRegistry.status})}),m=[],b=S(s.reasonCodes),w=fe(t,s.serverVersion);if(s.status==="incompatible"&&w===-1?m.push(d("error",n.CLIENT_TOO_OLD,"compatibility",l.clientTooOld,`client-version:${t}`)):s.status==="incompatible"&&w===1&&m.push(d("error",n.SERVER_TOO_OLD,"compatibility",l.serverTooOld,`server-version:${s.serverVersion}`)),b.some(y=>y.includes("protocol"))&&m.push(d("error",n.PROTOCOL_MISMATCH,"compatibility",l.protocol)),b.some(y=>y.includes("schema"))&&m.push(d("error",n.SCHEMA_MISMATCH,"compatibility",l.schema)),b.some(y=>y.includes("capability"))&&m.push(d("error",n.CAPABILITY_MISMATCH,"compatibility",l.capability)),(s.commandRegistry.status==="mismatched"||s.commandRegistry.version!==C||s.commandRegistry.checksum!==A)&&m.push(d("error",n.REGISTRY_DRIFT,"compatibility",l.registry,`sha256:${s.commandRegistry.checksum}`)),s.status==="incompatible"&&m.length===0)m.push(d("error",n.MALFORMED_RESPONSE,"compatibility",l.malformed));else if(s.status==="degraded")for(const y of b)m.push(d("warning",y,"compatibility",l.lifecycle));let N=q(),V=null,j=null,M=!1;if(a.releaseLifecycle===void 0)m.push(d("warning",n.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle));else{const y=i.validateReleaseLifecycle(a.releaseLifecycle),R=y.accepted?pe(y.projection):null;if(R){V=R.candidateId,j=R.lineageSha256;const O={};for(const _ of v){const h=R[_];if(O[_]=Object.freeze({value:h.value,freshness:h.freshness,reasonCodes:S(h.reasonCodes),evidenceRefs:$(h.evidenceRefs)}),h.value!==!0||h.freshness!=="fresh")for(const B of S(h.reasonCodes))m.push(d("warning",B,_,l.lifecycle,$(h.evidenceRefs)[0]??null))}N=Object.freeze(O)}else{M=!0,m.push(d("error",n.MALFORMED_RESPONSE,"releaseLifecycle",l.malformed));for(const O of S(y.reasonCodes))m.push(d("error",O,"releaseLifecycle",l.lifecycle))}}return m.length===0&&m.push(d("info",n.HEALTHY,"compatibility",l.healthy)),E({mode:"online",clientVersion:t,compatibility:p,dimensions:N,candidateId:V,lineageSha256:j,requiredDimension:e.requiredDimension,findings:m,incompatible:s.status==="incompatible"||M})}function Ce(e){const r=["Neocortex compatibility and release doctor (read-only)",`Result: ${e.overall} (exit ${e.exitCode})`,`Mode: ${e.mode}`,`Compatibility: ${e.compatibility.status}`,`Client: ${e.compatibility.clientVersion}`,`Server: ${e.compatibility.serverVersion??"unknown"}`,`Registry: ${e.compatibility.registry.status}`,"","Release lifecycle:"];for(const t of v){const i=e.release.dimensions[t];r.push(` ${t}: ${String(i.value)} (${i.freshness}) [${i.reasonCodes.join(",")||"none"}]`)}r.push("","Ordered findings:");for(const t of e.findings)r.push(` ${t.severity.toUpperCase()} ${t.reasonCode} dimension=${t.affectedDimension} evidence=${t.evidenceRef??"none"}`),r.push(` ${t.remediation}`);return r.push("","Doctor made no repairs or state changes."),r.join(`
2
- `)}async function Ve(e,r={}){const t=r.stdout??console.log,i=r.stderr??console.error;let o;try{o=ce(e,r.env??process.env)}catch(u){const f=u instanceof Error&&U.test(u.message)?u.message:"doctor-argument-invalid";return i(`Error: ${f}`),I.USAGE}const c=await Ae(o,r);return t(o.json?JSON.stringify(c,null,2):Ce(c)),c.exitCode}export{I as DOCTOR_EXIT_CODES,n as DOCTOR_REASON_CODES,Q as DOCTOR_RESPONSE_SCHEMA_VERSION,X as DOCTOR_SCHEMA_VERSION,Ne as __setDoctorClaudeWorktreeInspector,ue as collectLocalReleaseLifecycleContext,Ve as doctorCliHandler,de as loadSharedCompatibilityAuthority,ce as parseDoctorArgs,Ce as renderDoctorReport,Ae as runDoctor};
1
+ import{Buffer as I}from"node:buffer";import{createHash as x}from"node:crypto";import{execFileSync as J}from"node:child_process";import{readFileSync as Z,statSync as K}from"node:fs";import{join as Q,resolve as ee}from"node:path";import{COMMAND_REGISTRY_CHECKSUM as A,COMMAND_REGISTRY_VERSION as C}from"../generated/command-registry.generated.js";import{DEFAULT_SERVER_URL as U}from"../constants.js";import{getClientVersion as re}from"../version.js";import{inspectClaudeWorktreeBaseRef as te}from"../agent/claude-worktree-base.js";import{PRIVATE_EXECUTION_HOST_KINDS as oe}from"../../../shared/dist/compatibility/index.js";import{createPrivateHarnessExecutorPort as ie,resolvePrivateHarnessDecision as P}from"../private-execution/harness-adapters/index.js";const ne="CompatibilityReleaseDoctor/1.0",se="CompatibilityDoctorResponse/1.0",L=Object.freeze({SUCCESS:0,BLOCKED:1,USAGE:2}),s=Object.freeze({HEALTHY:"doctor-healthy",OFFLINE:"doctor-offline",SERVER_UNREACHABLE:"server-unreachable",CLIENT_TOO_OLD:"client-too-old",SERVER_TOO_OLD:"server-too-old",PROTOCOL_MISMATCH:"protocol-mismatch",SCHEMA_MISMATCH:"schema-mismatch",CAPABILITY_MISMATCH:"capability-mismatch",REGISTRY_DRIFT:"registry-drift",MALFORMED_RESPONSE:"malformed-response",AUTHORITY_UNAVAILABLE:"compatibility-authority-unavailable",RELEASE_LIFECYCLE_UNAVAILABLE:"release-lifecycle-unavailable",REQUIRED_DIMENSION_BLOCKED:"required-release-dimension-blocked",CLAUDE_WORKTREE_BASEREF_NOT_HEAD:"claude-worktree-baseref-not-head"}),D=Object.freeze(["implementationComplete","betaOperable","releaseReady","productionPromoted"]),ae=64*1024,ce=32,le=5e3,T=/^[a-z][a-z0-9-]{0,63}$/u,V=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,79}$/u,v=/^\d{1,6}\.\d{1,6}\.\d{1,6}(?:[-+][A-Za-z0-9.-]{1,40})?$/u,ue=/^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/u,F=/^[a-f0-9]{64}$/u,de=/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/u,fe=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u,me=/^(?:local-gate|beta-receipt|release-gate|promotion-receipt|sha256):[a-f0-9]{64}$/u,l=Object.freeze({healthy:"No compatibility remediation is required.",offline:"Rerun without --offline when read-only server evidence is available.",unreachable:"Check read-only server reachability, then rerun doctor.",clientTooOld:"Run a separately authorized client update, then rerun doctor.",serverTooOld:"Ask an authorized server operator to update the server, then rerun doctor.",protocol:"Align client and server protocol releases before invoking protected operations.",schema:"Use a client and server pair that supports the required public schemas.",capability:"Enable no feature here; use a release pair with the required capability set.",registry:"Install an exact release pair with the same command-registry checksum.",malformed:"Contact support with the reason code only; do not attach raw response data.",authority:"Integrate the P223.01 shared compatibility authority, then rerun doctor.",lifecycle:"Obtain bounded physical release evidence through separately authorized operations.",required:"Satisfy and verify the required physical release dimension through a separately authorized operation.",claudeWorktree:'Set Claude Code worktree.baseRef to "head" in ~/.claude/settings.json (neocortex refresh adds it when absent) so v4 story worktrees start from the epic checkout.'}),H=new Map([[s.MALFORMED_RESPONSE,0],[s.AUTHORITY_UNAVAILABLE,1],[s.CLIENT_TOO_OLD,2],[s.SERVER_TOO_OLD,3],[s.PROTOCOL_MISMATCH,4],[s.SCHEMA_MISMATCH,5],[s.CAPABILITY_MISMATCH,6],[s.REGISTRY_DRIFT,7],[s.SERVER_UNREACHABLE,8],[s.OFFLINE,9],[s.RELEASE_LIFECYCLE_UNAVAILABLE,10],[s.REQUIRED_DIMENSION_BLOCKED,11],[s.HEALTHY,100]]);function $(e="release-evidence-unavailable"){const r=()=>Object.freeze({value:"unknown",freshness:"unknown",reasonCodes:Object.freeze([e]),evidenceRefs:Object.freeze([])});return Object.freeze({implementationComplete:r(),betaOperable:r(),releaseReady:r(),productionPromoted:r()})}function pe(e){const r=Object.freeze({implementation:"implementationComplete","implementation-complete":"implementationComplete",beta:"betaOperable","beta-operable":"betaOperable",release:"releaseReady","release-ready":"releaseReady",production:"productionPromoted","production-promoted":"productionPromoted"});return e?r[e]??null:null}function ye(e,r=process.env){let t="online",o=!1,i=r.NEOCORTEX_SERVER_URL??U,c=!1,m=null,d=process.cwd();for(let n=0;n<e.length;n+=1){const a=e[n];if(a==="--offline")t="offline";else if(a==="--json")o=!0;else if(a==="--server-url"){const p=e[n+1];if(!p)throw new Error("doctor-server-url-required");i=p,c=!0,n+=1}else if(a==="--require"){const p=e[n+1],f=pe(p);if(!p||!f)throw new Error("doctor-required-dimension-invalid");m=f,n+=1}else if(a==="--project-root"){const p=e[n+1];if(!p||p.length>4096||p.includes("\0"))throw new Error("doctor-project-root-invalid");d=ee(p),n+=1}else throw new Error("doctor-argument-invalid")}if(t==="offline"&&c)throw new Error("doctor-offline-server-url-conflict");if(t==="offline")return Object.freeze({mode:t,json:o,serverUrl:U,requiredDimension:m,projectRoot:d});if(i.length>2048)throw new Error("doctor-server-url-invalid");try{const n=new URL(i);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password||n.search||n.hash)throw new Error("url")}catch{throw new Error("doctor-server-url-invalid")}return Object.freeze({mode:t,json:o,serverUrl:i.replace(/\/+$/u,""),requiredDimension:m,projectRoot:d})}function Ee(e){if(!e||typeof e!="object")return!1;const r=e;return typeof r.createCompatibilityOffer=="function"&&typeof r.isCompatibilityResultV1=="function"&&typeof r.validateReleaseLifecycle=="function"}async function be(){const e=["@neocortex/shared/compatibility","../../../shared/dist/compatibility/index.js"];for(const r of e)try{const t=await import(r);if(Ee(t))return t}catch{}return null}function he(e,r){if(typeof r.createReleaseLifecycleContext!="function")return null;try{const t=Q(e,".neocortex","state.json"),o=K(t);if(!o.isFile()||o.size<=0||o.size>1024*1024)return null;const i=JSON.parse(Z(t,"utf8")),m=(i.config&&typeof i.config=="object"&&!Array.isArray(i.config)?i.config:i.project&&typeof i.project=="object"&&!Array.isArray(i.project)?i.project:null)?.project_id;if(typeof m!="string"||!de.test(m))return null;const d=J("git",["rev-parse","--verify","HEAD"],{cwd:e,encoding:"utf8",timeout:2e3,maxBuffer:1024,stdio:["ignore","pipe","ignore"]}).trim().toLowerCase();if(!fe.test(d))return null;const n=x("sha256").update("git-lineage-v1\0").update(d).digest("hex"),a=`candidate-${x("sha256").update("release-candidate-v1\0").update(m).update("\0").update(d).digest("hex").slice(0,32)}`;return r.createReleaseLifecycleContext({projectId:m,candidateId:a,lineageSha256:n})}catch{return null}}function u(e,r,t,o,i=null){return Object.freeze({severity:e,reasonCode:r,affectedDimension:t,evidenceRef:i,remediation:o})}function Re(e,r){if(!v.test(e)||!v.test(r))return null;const t=c=>c.split(/[-+]/u,1)[0].split(".").map(Number),o=t(e),i=t(r);for(let c=0;c<3;c+=1)if(o[c]!==i[c])return o[c]<i[c]?-1:1;return 0}function g(e){return Object.freeze([...new Set(e.filter(r=>T.test(r)))].slice(0,8).sort())}function q(e){return Object.freeze([...new Set(e.filter(r=>V.test(r)))].slice(0,32).sort())}function B(e){return Object.freeze([...new Set(e.filter(r=>me.test(r)))].slice(0,8).sort())}function Oe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e,t=r.commandRegistry;return!["compatible","degraded","incompatible"].includes(String(r.status))||typeof r.clientVersion!="string"||!v.test(r.clientVersion)||typeof r.serverVersion!="string"||!v.test(r.serverVersion)||!(r.protocolVersion===null||typeof r.protocolVersion=="string"&&V.test(r.protocolVersion))||!Array.isArray(r.schemaVersions)||!r.schemaVersions.every(o=>typeof o=="string")||!Array.isArray(r.capabilityIds)||!r.capabilityIds.every(o=>typeof o=="string")||!Array.isArray(r.reasonCodes)||!r.reasonCodes.every(o=>typeof o=="string")||!t||typeof t.version!="string"||!ue.test(t.version)||typeof t.checksum!="string"||!F.test(t.checksum)||!["matched","mismatched","unknown"].includes(String(t.status))?null:r}function Ae(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e;if(typeof r.candidateId!="string"||!V.test(r.candidateId)||typeof r.lineageSha256!="string"||!F.test(r.lineageSha256))return null;for(const t of D){const o=r[t];if(!o||typeof o!="object"||Array.isArray(o))return null;const i=o;if(!(typeof i.value=="boolean"||i.value==="unknown")||!["fresh","stale","unknown"].includes(String(i.freshness))||!Array.isArray(i.reasonCodes)||!i.reasonCodes.every(c=>typeof c=="string")||!Array.isArray(i.evidenceRefs)||!i.evidenceRefs.every(c=>typeof c=="string"))return null}return r}function Ce(e){const r={error:0,warning:1,info:2},t=new Map([["compatibility",0],["releaseLifecycle",1],["implementationComplete",2],["betaOperable",3],["releaseReady",4],["productionPromoted",5]]);return Object.freeze([...e].sort((o,i)=>r[o.severity]-r[i.severity]||(H.get(o.reasonCode)??50)-(H.get(i.reasonCode)??50)||(t.get(o.affectedDimension)??99)-(t.get(i.affectedDimension)??99)||o.reasonCode.localeCompare(i.reasonCode)).slice(0,ce))}function ve(e){return Object.freeze({status:"unknown",clientVersion:e,serverVersion:null,protocolVersion:null,schemaVersions:Object.freeze([]),capabilityIds:Object.freeze([]),registry:Object.freeze({localVersion:C,localChecksum:A,remoteVersion:null,remoteChecksum:null,status:"unknown"})})}let w=()=>te();function Be(e){const r=w;return w=e,r}function ge(){let e;try{e=w()}catch{e="unknown"}return e==="absent"||e==="user-value"||e==="settings-invalid"?[u("warning",s.CLAUDE_WORKTREE_BASEREF_NOT_HEAD,"compatibility",l.claudeWorktree,null)]:[]}function E(e){const r=[...e.findings,...ge()],t=e.dimensions??$();let o=e.incompatible;e.requiredDimension&&t[e.requiredDimension].value!==!0&&(o=!0,r.push(u("error",s.REQUIRED_DIMENSION_BLOCKED,e.requiredDimension,l.required,t[e.requiredDimension].evidenceRefs[0]??null)));const i=Ce(r),c=o?"incompatible":i.some(m=>m.severity==="warning")?"degraded":"healthy";return Object.freeze({schemaVersion:ne,publicSafe:!0,readOnly:!0,mode:e.mode,overall:c,exitCode:o?L.BLOCKED:L.SUCCESS,compatibility:e.compatibility??ve(e.clientVersion),release:Object.freeze({candidateId:e.candidateId??null,lineageSha256:e.lineageSha256??null,requiredDimension:e.requiredDimension,dimensions:t}),findings:i})}function Se(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e;return"compatibility"in r?r.schemaVersion!==void 0&&r.schemaVersion!==se?null:{compatibility:r.compatibility,...r.releaseLifecycle!==void 0?{releaseLifecycle:r.releaseLifecycle}:{}}:{compatibility:e}}async function _e(e,r,t,o){const i=new AbortController,c=setTimeout(()=>i.abort(),le);try{const m=I.from(JSON.stringify(t),"utf8").toString("base64url");if(m.length>8192)return{kind:"malformed"};const d=o===null?null:I.from(JSON.stringify(o),"utf8").toString("base64url");if(d&&d.length>2048)return{kind:"malformed"};const n=await e(`${r}/api/v1/compatibility`,{method:"GET",headers:Object.freeze({Accept:"application/json","Cache-Control":"no-store","X-Neocortex-Compatibility-Offer":m,...d?{"X-Neocortex-Release-Context":d}:{}}),signal:i.signal});if(n.status===404||n.status===405||n.status===426)return{kind:"server-too-old"};if(!n.ok)return n.status>=500?{kind:"unreachable"}:{kind:"malformed"};const a=await n.text();if(I.byteLength(a,"utf8")>ae)return{kind:"malformed"};try{return{kind:"ok",value:JSON.parse(a)}}catch{return{kind:"malformed"}}}catch{return{kind:"unreachable"}}finally{clearTimeout(c)}}function Ie(e,r){return E({mode:"offline",clientVersion:e,requiredDimension:r,incompatible:!1,findings:[u("warning",s.OFFLINE,"compatibility",l.offline),u("warning",s.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]})}const Y="private-executor-headless-unavailable",G="private-executor-version-unsupported",X=/^\d{1,9}\.\d{1,9}\.\d{1,9}$/u,S=Object.freeze({availability:"absent",version:null,refusalReasonCode:null});async function Le(e,r={}){try{const o=P(e)?.kind==="adapter"?ie(e,r):void 0;if(o===void 0)return Object.freeze({availability:"refused",version:null,refusalReasonCode:Y});const i=await o.preflight();return X.test(i.hostVersion)?Object.freeze({availability:"available",version:i.hostVersion,refusalReasonCode:null}):S}catch(t){return t instanceof Error&&t.message===G?Object.freeze({availability:"refused",version:null,refusalReasonCode:G}):S}}function De(e){if(!e||typeof e!="object"||Array.isArray(e))return S;const r=e,t=r.version,o=r.refusalReasonCode;return r.availability==="available"&&typeof t=="string"&&X.test(t)&&o===null?Object.freeze({availability:"available",version:t,refusalReasonCode:null}):r.availability==="refused"&&t===null&&typeof o=="string"&&T.test(o)?Object.freeze({availability:"refused",version:null,refusalReasonCode:o}):S}async function Te(e,r){const t=r.probePrivateExecutor,o=await Promise.all(oe.map(async i=>{if(t===void 0)return Object.freeze({hostKind:i,...P(i)?.kind==="refusal"?{availability:"refused",version:null,refusalReasonCode:Y}:{availability:"not-probed",version:null,refusalReasonCode:null}});let c;try{c=await t(i)}catch{c=void 0}return Object.freeze({hostKind:i,...De(c)})}));return Object.freeze(o)}async function Ve(e,r={}){const[t,o]=await Promise.all([we(e,r),Te(e.projectRoot,r)]);return Object.freeze({...t,privateExecutors:o})}async function we(e,r){const t=(r.getClientVersion??re)();if(e.mode==="offline")return Ie(t,e.requiredDimension);const o=await(r.loadCompatibilityAuthority??be)();if(!o)return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.AUTHORITY_UNAVAILABLE,"compatibility",l.authority)]});let i;try{i=o.createCompatibilityOffer({clientVersion:t,registryVersion:C,registryChecksum:A})}catch{return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.AUTHORITY_UNAVAILABLE,"compatibility",l.authority)]})}const c=(r.collectReleaseContext??he)(e.projectRoot,o),m=r.fetch??globalThis.fetch,d=await _e(m,e.serverUrl,i,c);if(d.kind==="unreachable")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!1,findings:[u("warning",s.SERVER_UNREACHABLE,"compatibility",l.unreachable),u("warning",s.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]});if(d.kind==="server-too-old")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.SERVER_TOO_OLD,"compatibility",l.serverTooOld),u("warning",s.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle)]});if(d.kind==="malformed")return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const n=Se(d.value);if(!n||!o.isCompatibilityResultV1(n.compatibility))return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const a=Oe(n.compatibility);if(!a||a.clientVersion!==t)return E({mode:"online",clientVersion:t,requiredDimension:e.requiredDimension,incompatible:!0,findings:[u("error",s.MALFORMED_RESPONSE,"compatibility",l.malformed)]});const p=Object.freeze({status:a.status,clientVersion:t,serverVersion:a.serverVersion,protocolVersion:a.protocolVersion,schemaVersions:q(a.schemaVersions),capabilityIds:q(a.capabilityIds),registry:Object.freeze({localVersion:C,localChecksum:A,remoteVersion:a.commandRegistry.version,remoteChecksum:a.commandRegistry.checksum,status:a.commandRegistry.status})}),f=[],h=g(a.reasonCodes),j=Re(t,a.serverVersion);if(a.status==="incompatible"&&j===-1?f.push(u("error",s.CLIENT_TOO_OLD,"compatibility",l.clientTooOld,`client-version:${t}`)):a.status==="incompatible"&&j===1&&f.push(u("error",s.SERVER_TOO_OLD,"compatibility",l.serverTooOld,`server-version:${a.serverVersion}`)),h.some(y=>y.includes("protocol"))&&f.push(u("error",s.PROTOCOL_MISMATCH,"compatibility",l.protocol)),h.some(y=>y.includes("schema"))&&f.push(u("error",s.SCHEMA_MISMATCH,"compatibility",l.schema)),h.some(y=>y.includes("capability"))&&f.push(u("error",s.CAPABILITY_MISMATCH,"compatibility",l.capability)),(a.commandRegistry.status==="mismatched"||a.commandRegistry.version!==C||a.commandRegistry.checksum!==A)&&f.push(u("error",s.REGISTRY_DRIFT,"compatibility",l.registry,`sha256:${a.commandRegistry.checksum}`)),a.status==="incompatible"&&f.length===0)f.push(u("error",s.MALFORMED_RESPONSE,"compatibility",l.malformed));else if(a.status==="degraded")for(const y of h)f.push(u("warning",y,"compatibility",l.lifecycle));let N=$(),M=null,z=null,k=!1;if(n.releaseLifecycle===void 0)f.push(u("warning",s.RELEASE_LIFECYCLE_UNAVAILABLE,"releaseLifecycle",l.lifecycle));else{const y=o.validateReleaseLifecycle(n.releaseLifecycle),R=y.accepted?Ae(y.projection):null;if(R){M=R.candidateId,z=R.lineageSha256;const O={};for(const _ of D){const b=R[_];if(O[_]=Object.freeze({value:b.value,freshness:b.freshness,reasonCodes:g(b.reasonCodes),evidenceRefs:B(b.evidenceRefs)}),b.value!==!0||b.freshness!=="fresh")for(const W of g(b.reasonCodes))f.push(u("warning",W,_,l.lifecycle,B(b.evidenceRefs)[0]??null))}N=Object.freeze(O)}else{k=!0,f.push(u("error",s.MALFORMED_RESPONSE,"releaseLifecycle",l.malformed));for(const O of g(y.reasonCodes))f.push(u("error",O,"releaseLifecycle",l.lifecycle))}}return f.length===0&&f.push(u("info",s.HEALTHY,"compatibility",l.healthy)),E({mode:"online",clientVersion:t,compatibility:p,dimensions:N,candidateId:M,lineageSha256:z,requiredDimension:e.requiredDimension,findings:f,incompatible:a.status==="incompatible"||k})}function je(e){const r=["Neocortex compatibility and release doctor (read-only)",`Result: ${e.overall} (exit ${e.exitCode})`,`Mode: ${e.mode}`,`Compatibility: ${e.compatibility.status}`,`Client: ${e.compatibility.clientVersion}`,`Server: ${e.compatibility.serverVersion??"unknown"}`,`Registry: ${e.compatibility.registry.status}`,"","Release lifecycle:"];for(const t of D){const o=e.release.dimensions[t];r.push(` ${t}: ${String(o.value)} (${o.freshness}) [${o.reasonCodes.join(",")||"none"}]`)}r.push("","Ordered findings:");for(const t of e.findings)r.push(` ${t.severity.toUpperCase()} ${t.reasonCode} dimension=${t.affectedDimension} evidence=${t.evidenceRef??"none"}`),r.push(` ${t.remediation}`);r.push("","Private executors:");for(const t of e.privateExecutors)r.push(` ${t.hostKind}: ${t.availability} version=${t.version??"unknown"} refusal=${t.refusalReasonCode??"none"}`);return r.push("","Doctor made no repairs or state changes."),r.join(`
2
+ `)}async function Ye(e,r){const t=r??{},o=t.stdout??console.log,i=t.stderr??console.error;let c;try{c=ye(e,t.env??process.env)}catch(n){const a=n instanceof Error&&T.test(n.message)?n.message:"doctor-argument-invalid";return i(`Error: ${a}`),L.USAGE}const m=c.projectRoot,d=await Ve(c,r===void 0?{...t,probePrivateExecutor:n=>Le(n,{cwd:m})}:t);return o(c.json?JSON.stringify(d,null,2):je(d)),d.exitCode}export{L as DOCTOR_EXIT_CODES,s as DOCTOR_REASON_CODES,se as DOCTOR_RESPONSE_SCHEMA_VERSION,ne as DOCTOR_SCHEMA_VERSION,Be as __setDoctorClaudeWorktreeInspector,he as collectLocalReleaseLifecycleContext,Le as defaultProbePrivateExecutor,Ye as doctorCliHandler,be as loadSharedCompatibilityAuthority,ye as parseDoctorArgs,je as renderDoctorReport,Ve as runDoctor};